docs/figures/publish_bb144.py
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1#!/usr/bin/env python3
2"""Check or render the frozen BB144 documentation figures without simulation.
3
4--check uses only the Python standard library. Rendering (default, or --render) needs
5Matplotlib and writes SVG/PNG figures plus a rendering receipt in the bundle.
6It never reads build/generated or the sibling presentation repository.
7"""
8
9import argparse
10import csv
11import hashlib
12import json
13import math
14from pathlib import Path
15
16
17DEFAULT_BUNDLE = Path(__file__).resolve().parents[1] / "source/_static/bb144-results/legacy-v1"
18CSV_HASHES = {
19 "vanilla": "b09eeed3adc30aa241e96680df7502c90078e5f01fa9e08207f4fd5114813260",
20 "relay": "3cf54a4fecd1e14c335c7d6cd18fb6aa89dcfe3685cd23c7e5302d08a6a12ca9",
21 "budget": "4c19cbaa7da9343103f9d0902fb41e8abef128cfc0556c78f398eeedc03cabba",
22}
23COLORS = {"vanilla": "#2458a6", "relay": "#087e8b", "budget": "#ad4d20"}
24FIGURES = ("vanilla-rate", "relay-rate", "relay-budget")
25
26
27def require(condition, message):
28 if not condition:
29 raise ValueError(message)
30
31
32def sha256(path):
33 return hashlib.sha256(path.read_bytes()).hexdigest()
34
35
36def close(actual, expected, label):
37 require(math.isfinite(actual) and math.isclose(actual, expected, rel_tol=1e-11, abs_tol=1e-14),
38 f"{label}: {actual} != {expected}")
39
40
41def wilson(failures, shots):
42 z = 1.959963984540054
43 center = (failures / shots + z * z / (2 * shots)) / (1 + z * z / shots)
44 radius = z * math.sqrt(failures * (shots - failures) / shots**3
45 + z * z / (4 * shots**2)) / (1 + z * z / shots)
46 return max(0.0, center - radius), min(1.0, center + radius)
47
48
49def per_cycle(probability):
50 return 1.0 if probability == 1 else -math.expm1(math.log1p(-probability) / 12)
51
52
53def check_inputs(bundle):
54 manifest = json.loads((bundle / "manifest.json").read_text())
55 require(manifest["schema"] == "chipsldpc.docs.bb144-legacy-bundle.v1", "unexpected bundle schema")
56 require(manifest["records"] == {"vanilla": 7, "relay": 7, "budget": 8}, "unexpected record counts")
57 for name, record in manifest["files"].items():
58 path = bundle / name
59 require(path.is_file(), f"missing bundled input: {name}")
60 require(path.stat().st_size == record["bytes"] and sha256(path) == record["sha256"],
61 f"bundled input changed: {name}")
62 proof = json.loads((bundle / "presentation-provenance.json").read_text())
63 metadata = json.loads((bundle / "metadata.json").read_text())
64 rows = {}
65 for name, expected_hash in CSV_HASHES.items():
66 path = bundle / f"{name}.csv"
67 require(sha256(path) == expected_hash == proof["sources"][name]["sha256"],
68 f"{name}: CSV differs from the archived presentation data")
69 with path.open(newline="") as stream:
70 rows[name] = [{key: float(value) for key, value in row.items()}
71 for row in csv.DictReader(stream)]
72 require(len(rows[name]) == manifest["records"][name], f"{name}: wrong row count")
73 profile = metadata["profiles"][name]
74 require(profile["schema"] == "chipsldpc.bb144.v2", f"{name}: wrong historical schema")
75 require(profile["sampling"]["seed"] == 14412, f"{name}: unexpected seed")
76 expected_shots = 20000 if name == "budget" else 1000
77 require(profile["sampling"]["shots_per_p"] == expected_shots, f"{name}: wrong shots metadata")
78 require((profile["dem"]["m"], profile["dem"]["n"], profile["dem"]["e"])
79 == (936, 8784, 30672), f"{name}: wrong reduced graph")
80 require((profile["dem"]["raw_m"], profile["dem"]["raw_n"],
81 profile["dem"]["logical_observables"], profile["dem"]["singleton_eliminations"])
82 == (1008, 8856, 12, 72), f"{name}: wrong model dimensions")
83 config = json.loads((bundle / f"{name}-config.json").read_text())
84 require((config["message_bits"], config["soft_bits"], config["m"], config["n"])
85 == (4, 7 if name == "vanilla" else 5, 936, 8784), f"{name}: wrong arithmetic profile")
86 if name == "vanilla":
87 require(config["iterations"] == 30, "vanilla: wrong iteration cap")
88 else:
89 initial, relay_r = (80, 600) if name == "relay" else (60, 67)
90 require((config["initial_iterations"], config["relay_iterations"],
91 config["paper_R_relay_legs_after_initial"], config["solution_target"],
92 config["seed_offset"], config["maximum_legs_total"], config["maximum_total_iterations"])
93 == (initial, 60, relay_r, 5, 0, relay_r + 1, initial + 60 * relay_r),
94 f"{name}: wrong Relay profile")
95 for index, row in enumerate(rows[name]):
96 label = f"{name}[{index}]"
97 shots, failures = row["shots"], row["failures"]
98 require(shots == expected_shots and failures.is_integer() and 0 <= failures <= shots,
99 f"{label}: invalid counts")
100 close(row["word_failure_probability"], failures / shots, label + " word probability")
101 low, high = wilson(failures, shots)
102 close(row["word_failure_ci95_low"], low, label + " Wilson lower bound")
103 close(row["word_failure_ci95_high"], high, label + " Wilson upper bound")
104 if name != "budget":
105 close(row["logical_failure_rate_per_qec_cycle"], per_cycle(failures / shots), label + " rate")
106 close(row["logical_rate_ci95_low"], per_cycle(low), label + " rate lower bound")
107 close(row["logical_rate_ci95_high"], per_cycle(high), label + " rate upper bound")
108 require(row["bp_nonconverged"] + row["bp_converged_logical_failures"] == failures,
109 label + ": failure components disagree")
110 else:
111 require(row["max_bp_iterations"] == 60 * (row["paper_R"] + 1), label + ": wrong budget")
112 require(0 < row["mean_executed_iterations"] <= row["max_bp_iterations"], label + ": invalid mean")
113 require(row["mean_iterations_ci95_half_width"] >= 0, label + ": invalid mean interval")
114 expected_p = [.003] if name == "budget" else [i / 1000 for i in range(1, 8)]
115 require(profile["sampling"]["p_values"] == expected_p, f"{name}: wrong physical probability points")
116 if name != "budget":
117 require([row["p"] for row in rows[name]] == expected_p, f"{name}: wrong CSV probability points")
118 expected_r = [0, 1, 2, 4, 8, 16, 33, 67]
119 require([row["paper_R"] for row in rows["budget"]] == metadata["budget"]["R"] == expected_r,
120 "wrong budget R values")
121 require([row["max_bp_iterations"] for row in rows["budget"]] == metadata["budget"]["max_bp_iterations"],
122 "budget metadata differs from CSV")
123 require([row["p"] for row in rows["relay"] if row["failures"] == 0] == [.001, .002],
124 "unexpected zero-failure points")
125 return rows
126
127
128def check_figures(bundle):
129 receipt = json.loads((bundle / "figures.json").read_text())
130 require(receipt["manifest_sha256"] == sha256(bundle / "manifest.json"), "figures use a different manifest")
131 require(receipt["renderer_sha256"] == sha256(Path(__file__)), "renderer changed; regenerate figures")
132 expected = {f"{name}.{suffix}" for name in FIGURES for suffix in ("svg", "png")}
133 require(set(receipt["figures"]) == expected, "incomplete figure set")
134 for name, digest in receipt["figures"].items():
135 require(sha256(bundle / name) == digest, f"figure changed: {name}")
136
137
138def render(bundle, rows):
139 import matplotlib
140 matplotlib.use("Agg")
141 import matplotlib.pyplot as plt
142 from matplotlib.ticker import NullFormatter, ScalarFormatter
143
144 plt.rcParams.update({"font.size": 11, "axes.titlesize": 15, "axes.labelsize": 11,
145 "font.family": "DejaVu Sans", "svg.fonttype": "none",
146 "svg.hashsalt": "chipsldpc-bb144-legacy-v1", "axes.spines.top": False,
147 "axes.spines.right": False, "savefig.facecolor": "white"})
148
149 def save(figure, name):
150 figure.savefig(bundle / f"{name}.svg", metadata={"Date": None})
151 figure.savefig(bundle / f"{name}.png", dpi=180)
152 plt.close(figure)
153
154 for name, title, subtitle in (
155 ("vanilla", "Vanilla BP", "30-iteration cap · 1,000 shots per point"),
156 ("relay", "Relay-5", r"$T_0=80$, $T_r=60$, $R=600$ · 1,000 shots per point")):
157 figure, axis = plt.subplots(figsize=(8, 4.8), layout="constrained")
158 positive = [row for row in rows[name] if row["failures"] > 0]
159 x = [100 * row["p"] for row in positive]
160 y = [row["logical_failure_rate_per_qec_cycle"] for row in positive]
161 axis.errorbar(x, y, yerr=([row["logical_failure_rate_per_qec_cycle"] - row["logical_rate_ci95_low"]
162 for row in positive],
163 [row["logical_rate_ci95_high"] - row["logical_failure_rate_per_qec_cycle"]
164 for row in positive]),
165 fmt="o-", color=COLORS[name], linewidth=1.7, markersize=5,
166 capsize=3, label="Estimate with Wilson 95% interval")
167 zero = [row for row in rows[name] if row["failures"] == 0]
168 if zero:
169 axis.scatter([100 * row["p"] for row in zero], [row["logical_rate_ci95_high"] for row in zero],
170 marker="v", s=55, facecolors="white", edgecolors=COLORS[name], linewidths=1.5,
171 label="Zero failures: upper Wilson 95% bound", zorder=3)
172 axis.set(yscale="log", xlabel="Physical error probability p (%)",
173 ylabel=r"Equivalent per-cycle failure, $q_{\mathrm{equiv}}$",
174 xticks=[i / 10 for i in range(1, 8)], xlim=(.075, .725))
175 axis.set_title(title + "\n" + subtitle, loc="left", pad=12)
176 axis.grid(True, which="both", alpha=.2)
177 axis.legend(loc="best", fontsize=9, frameon=True, framealpha=.95)
178 save(figure, name + "-rate")
179
180 data = rows["budget"]
181 figure, axis = plt.subplots(figsize=(8, 4.9), layout="constrained")
182 x = [row["mean_executed_iterations"] for row in data]
183 y = [row["word_failure_probability"] for row in data]
184 axis.errorbar(x, y, xerr=[row["mean_iterations_ci95_half_width"] for row in data],
185 yerr=([row["word_failure_probability"] - row["word_failure_ci95_low"] for row in data],
186 [row["word_failure_ci95_high"] - row["word_failure_probability"] for row in data]),
187 fmt="o-", color=COLORS["budget"], linewidth=1.7, markersize=5, capsize=3)
188 for index, row in enumerate(data):
189 axis.annotate(f"R={int(row['paper_R'])}", (x[index], y[index]),
190 xytext=(7, 9 if index < 4 else 5), textcoords="offset points", fontsize=9)
191 axis.set(xscale="log", yscale="log", xlabel="Mean executed BP iterations per shot",
192 ylabel=r"Word-failure probability, $P_{\mathrm{word}}$", xlim=(11, 142), ylim=(.00042, .055))
193 axis.set_xticks([15, 20, 30, 50, 75, 100])
194 axis.xaxis.set_major_formatter(ScalarFormatter())
195 axis.xaxis.set_minor_formatter(NullFormatter())
196 axis.set_title("Relay-5: iteration-budget sweep\n"
197 r"$p=0.3\%$, $T_0=T_r=60$, $B=60(R+1)$ · 20,000 shots per point", loc="left", pad=12)
198 axis.grid(True, which="both", alpha=.2)
199 save(figure, "relay-budget")
200 receipt = {"schema": "chipsldpc.docs.bb144-figures.v1",
201 "manifest_sha256": sha256(bundle / "manifest.json"),
202 "renderer_sha256": sha256(Path(__file__)), "matplotlib": matplotlib.__version__,
203 "figures": {f"{name}.{suffix}": sha256(bundle / f"{name}.{suffix}")
204 for name in FIGURES for suffix in ("svg", "png")}}
205 (bundle / "figures.json").write_text(json.dumps(receipt, indent=2) + "\n")
206
207
208def main():
209 parser = argparse.ArgumentParser(description=__doc__)
210 action = parser.add_mutually_exclusive_group()
211 action.add_argument("--check", action="store_true", help="verify frozen inputs, formulas and existing figures; stdlib only")
212 action.add_argument("--render", action="store_true", help="validate inputs and regenerate the six SVG/PNG files")
213 parser.add_argument("--bundle", type=Path, default=DEFAULT_BUNDLE)
214 args = parser.parse_args()
215 rows = check_inputs(args.bundle)
216 if not args.check:
217 render(args.bundle, rows)
218 check_figures(args.bundle)
219 print("PASS: 22 archived records, profile settings, Wilson intervals, rate transforms, budgets and figure hashes.")
220 print("The saved horizontal mean intervals are hash-checked; raw iteration samples are not bundled.")
221
222
223if __name__ == "__main__":
224 main()