-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc_generator.py
More file actions
670 lines (614 loc) · 25.9 KB
/
Copy pathdoc_generator.py
File metadata and controls
670 lines (614 loc) · 25.9 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
"""doc_generator.py — Professional documentation generator for QECTOR codes.
Generates Markdown, JSON, HTML, LaTeX, PDF (matplotlib multi-page) and SVG
documentation for a QEC code object. All outputs land in a per-user writable
export directory (``utils.get_export_dir()``) unless an explicit
``output_dir`` is supplied. Decoder recommendations are measured on the code
actually being documented, and every code-derived string is escaped for the
target format (``html.escape`` for HTML, :func:`latex_escape` for LaTeX).
"""
from __future__ import annotations
import html
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
import numpy as np
import utils
from version import DOC_GENERATOR_VERSION, FULL_VERSION
try:
import backend as be
_HAS_BACKEND = True
except Exception:
_HAS_BACKEND = False
WATERMARK = "QECTOR CERTIFIED - PROVENANCE INTACT"
#: Number of timed single-shot decodes per decoder for the recommendations table.
RECOMMENDATION_TRIALS = 25
#: Physical error rate used for the recommendation timing loop.
RECOMMENDATION_ERROR_RATE = 0.05
#: Base seed for the recommendation timing loop (seed = base + trial index).
RECOMMENDATION_SEED_BASE = 1000
_LATEX_SPECIALS = {
"\\": r"\textbackslash{}",
"&": r"\&",
"%": r"\%",
"$": r"\$",
"#": r"\#",
"_": r"\_",
"{": r"\{",
"}": r"\}",
"~": r"\textasciitilde{}",
"^": r"\textasciicircum{}",
}
def latex_escape(value: Any) -> str:
"""Escape LaTeX special characters (\\ & % $ # _ { } ~ ^) in ``value``."""
return "".join(_LATEX_SPECIALS.get(ch, ch) for ch in str(value))
def _html_escape(value: Any) -> str:
"""HTML-escape the string form of ``value`` (including quotes)."""
return html.escape(str(value), quote=True)
def _md_cell(value: Any) -> str:
"""Sanitise a value for use inside a Markdown table cell."""
return str(value).replace("|", "\\|").replace("\r", " ").replace("\n", " ")
def _mpl_text(value: Any) -> str:
"""Sanitise a string for matplotlib text (avoid accidental mathtext)."""
return str(value).replace("$", r"\$")
def _safe_attr(obj, attr: str, default: Any = "") -> Any:
return getattr(obj, attr, default)
def _code_metadata(code) -> dict[str, Any]:
"""Collect display metadata from a code object; bound methods are called."""
md: dict[str, Any] = {}
for k in ("n_qubits", "n_checks", "distance", "name", "description", "max_qubit_degree"):
try:
v = getattr(code, k, None)
if callable(v):
v = v()
except Exception:
v = None
if v is not None:
md[k] = v
md.setdefault("n_qubits", 0)
md.setdefault("n_checks", 0)
return md
def _rate_str(nq: int, nc: int) -> str:
try:
return f"{1 - nc / max(int(nq), 1):.4f}" if nq else "N/A"
except Exception:
return "N/A"
def _parity_check_dense(code) -> Optional[np.ndarray]:
"""Return the parity-check matrix as a dense 2-D ndarray, or None.
Handles both attribute-style and callable-style ``parity_check_matrix``
(falling back to ``H``), and both dense and sparse (todense/toarray)
representations.
"""
mat = getattr(code, "parity_check_matrix", None)
if mat is None:
mat = getattr(code, "H", None)
if mat is None:
return None
try:
if callable(mat):
mat = mat()
if mat is None:
return None
if hasattr(mat, "toarray"):
mat = mat.toarray()
elif hasattr(mat, "todense"):
mat = mat.todense()
arr = np.asarray(mat)
if arr.ndim != 2 or arr.size == 0:
return None
return arr
except Exception:
return None
def _provenance_block() -> str:
return (
f"Generated by {FULL_VERSION}\n"
f"Doc Generator v{DOC_GENERATOR_VERSION}\n"
f"Timestamp: {datetime.now(timezone.utc).isoformat()}\n"
f"Watermark: {WATERMARK}\n"
)
class ProfessionalDocGenerator:
"""Professional multi-format documentation generator for QEC codes."""
def __init__(self, output_dir: Optional[Path] = None):
self.version = DOC_GENERATOR_VERSION
if output_dir is None:
self.output_dir = utils.get_export_dir()
else:
self.output_dir = Path(output_dir)
try:
self.output_dir.mkdir(parents=True, exist_ok=True)
except Exception:
# Per-format writes will report failure honestly if the
# directory truly cannot be created.
pass
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def generate_all(self, code, formats: list[str]) -> dict[str, tuple[bool, Path]]:
"""Generate documentation in each requested format.
Returns ``{fmt: (ok, path)}`` where ``ok`` is False (with an empty
path) for unknown formats or per-format failures. Never raises for a
single failing format.
"""
results: dict[str, tuple[bool, Path]] = {}
md = _code_metadata(code)
nq = md.get("n_qubits", 0)
nc = md.get("n_checks", 0)
recs = self._benchmark_decoders(code)
try:
self.output_dir.mkdir(parents=True, exist_ok=True)
except Exception:
pass
stem = f"code_doc_{nq}q_{nc}c"
text_builders = {
"markdown": (".md", self._generate_markdown),
"json": (".json", self._generate_json),
"html": (".html", self._generate_html),
"latex": (".tex", self._generate_latex),
}
for fmt in formats:
try:
if fmt in text_builders:
suffix, builder = text_builders[fmt]
path = self.output_dir / (stem + suffix)
content = builder(code, md, nq, nc, recs)
path.write_text(content, encoding="utf-8")
elif fmt == "pdf":
path = self.output_dir / (stem + ".pdf")
self._generate_pdf(code, md, nq, nc, recs, path)
elif fmt == "svg":
path = self.output_dir / (stem + ".svg")
self._generate_svg(code, md, path)
else:
results[fmt] = (False, Path())
continue
results[fmt] = (True, path.resolve())
except Exception:
results[fmt] = (False, Path())
return results
# ------------------------------------------------------------------
# Decoder recommendations — measured on THE PASSED CODE
# ------------------------------------------------------------------
def _benchmark_decoders(
self,
code,
n_trials: int = RECOMMENDATION_TRIALS,
error_rate: float = RECOMMENDATION_ERROR_RATE,
) -> list[dict[str, Any]]:
"""Time each decoder kind on the code being documented.
For every kind in ``backend.DECODER_KINDS`` runs ``n_trials`` seeded
single-shot decodes on ``code`` and reports mean latency (ms) plus the
observed logical-failure fraction. Per-decoder failures are recorded
honestly as ``unavailable: <reason>``.
"""
rows: list[dict[str, Any]] = []
if not _HAS_BACKEND:
return rows
for kind in be.DECODER_KINDS:
try:
description = be.get_decoder_info(kind).get("description", "")
except Exception:
description = ""
try:
latencies_s: list[float] = []
failures = 0
observed = 0
for i in range(n_trials):
t0 = time.perf_counter()
out = be.run_single_decode(
code, error_rate, kind, seed=RECOMMENDATION_SEED_BASE + i
)
latencies_s.append(time.perf_counter() - t0)
lf = out["result"].logical_failure
if lf is not None:
observed += 1
if lf:
failures += 1
mean_ms = 1000.0 * sum(latencies_s) / len(latencies_s)
rows.append(
{
"decoder": kind,
"description": description,
"status": "ok",
"n_trials": n_trials,
"error_rate": error_rate,
"mean_latency_ms": round(mean_ms, 4),
"logical_failure_fraction": (failures / observed) if observed else None,
}
)
except Exception as exc:
rows.append(
{
"decoder": kind,
"description": description,
"status": f"unavailable: {exc}",
"n_trials": n_trials,
"error_rate": error_rate,
"mean_latency_ms": None,
"logical_failure_fraction": None,
}
)
return rows
@staticmethod
def _rec_display(row: dict[str, Any]) -> tuple[str, str, str, str]:
"""Return (decoder, latency, failure-fraction, note) display strings."""
decoder = str(row.get("decoder", ""))
if row.get("status") == "ok":
latency = f"{row['mean_latency_ms']:.3f} ms"
lff = row.get("logical_failure_fraction")
failure = "N/A (no logicals matrix)" if lff is None else f"{lff:.3f}"
note = f"{row.get('n_trials')} trials @ p={row.get('error_rate')}"
else:
latency = "n/a"
failure = "n/a"
note = str(row.get("status", "unavailable"))
return decoder, latency, failure, note
# ------------------------------------------------------------------
# Markdown
# ------------------------------------------------------------------
def _generate_markdown(self, code, md: dict, nq: int, nc: int, recs: list[dict]) -> str:
lines = [
"# QECTOR Code Documentation",
"",
f"**{FULL_VERSION} — Doc Generator v{DOC_GENERATOR_VERSION}**",
"",
"---",
"",
"## Code Summary",
"",
"| Property | Value |",
"|----------|-------|",
f"| Qubits | {_md_cell(nq)} |",
f"| Checks | {_md_cell(nc)} |",
f"| Distance | {_md_cell(md.get('distance', 'N/A'))} |",
f"| Name | {_md_cell(md.get('name', 'N/A'))} |",
f"| Max qubit degree | {_md_cell(md.get('max_qubit_degree', 'N/A'))} |",
"",
"## Code Analysis",
"",
f"- **Rate**: {_md_cell(_rate_str(nq, nc))}",
f"- **Parity Check Matrix**: {_md_cell(nc)}×{_md_cell(nq)}",
"",
"## Decoder Recommendations",
"",
f"Measured on this code ({_md_cell(md.get('name', 'unnamed'))}): "
f"{RECOMMENDATION_TRIALS} seeded single-shot decodes per decoder at "
f"p={RECOMMENDATION_ERROR_RATE}.",
"",
"| Decoder | Mean latency | Logical failure fraction | Notes |",
"|---------|--------------|--------------------------|-------|",
]
if recs:
for row in recs:
decoder, latency, failure, note = self._rec_display(row)
lines.append(
f"| {_md_cell(decoder)} | {_md_cell(latency)} | "
f"{_md_cell(failure)} | {_md_cell(note)} |"
)
else:
lines.append("| (backend unavailable) | n/a | n/a | n/a |")
lines += ["", "---", "", "## Provenance", "", _provenance_block()]
return "\n".join(lines)
# ------------------------------------------------------------------
# JSON
# ------------------------------------------------------------------
def _generate_json(self, code, md: dict, nq: int, nc: int, recs: list[dict]) -> str:
doc = {
"generator": FULL_VERSION,
"doc_generator_version": DOC_GENERATOR_VERSION,
"timestamp": datetime.now(timezone.utc).isoformat(),
"watermark": WATERMARK,
"code": {
"n_qubits": nq,
"n_checks": nc,
"distance": md.get("distance"),
"name": md.get("name"),
"description": md.get("description"),
"max_qubit_degree": md.get("max_qubit_degree"),
},
"analysis": {
"parity_check_matrix_shape": [nc, nq],
"rate": _rate_str(nq, nc),
},
"recommendations": recs,
}
return json.dumps(doc, indent=2, default=str)
# ------------------------------------------------------------------
# HTML — every interpolated value passes through html.escape
# ------------------------------------------------------------------
def _generate_html(self, code, md: dict, nq: int, nc: int, recs: list[dict]) -> str:
props_rows = "".join(
f"<tr><td>{_html_escape(k)}</td><td>{_html_escape(v)}</td></tr>\n"
for k, v in [
("Qubits", nq),
("Checks", nc),
("Distance", md.get("distance", "N/A")),
("Name", md.get("name", "N/A")),
("Max qubit degree", md.get("max_qubit_degree", "N/A")),
]
)
props = f"<table>\n{props_rows}</table>"
analysis_html = f"""<h2>Code Analysis</h2>
<table>
<tr><th>Metric</th><th>Value</th></tr>
<tr><td>Rate</td><td>{_html_escape(_rate_str(nq, nc))}</td></tr>
<tr><td>Parity Check Matrix</td><td>{_html_escape(nc)}×{_html_escape(nq)}</td></tr>
</table>"""
if recs:
rec_rows = "".join(
"<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n".format(
*(_html_escape(v) for v in self._rec_display(row))
)
for row in recs
)
else:
rec_rows = "<tr><td colspan=\"4\">backend unavailable</td></tr>\n"
recs_html = f"""<h2>Decoder Recommendations</h2>
<p>Measured on this code ({_html_escape(md.get('name', 'unnamed'))}):
{RECOMMENDATION_TRIALS} seeded single-shot decodes per decoder at
p={RECOMMENDATION_ERROR_RATE}.</p>
<table>
<tr><th>Decoder</th><th>Mean latency</th><th>Logical failure fraction</th><th>Notes</th></tr>
{rec_rows}</table>"""
provenance_html = _html_escape(_provenance_block()).replace("\n", "<br>")
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>QECTOR Code Documentation</title>
<style>
body {{ font-family: 'Segoe UI', Arial, sans-serif; max-width: 900px; margin: 40px auto; padding: 0 20px; color: #222; }}
h1 {{ color: #1a3c6e; border-bottom: 2px solid #4a9eff; padding-bottom: 8px; }}
h2 {{ color: #2a5a9e; margin-top: 30px; }}
table {{ border-collapse: collapse; width: 100%; margin: 16px 0; }}
th, td {{ border: 1px solid #ccc; padding: 8px 12px; text-align: left; }}
th {{ background: #e8f0fe; }}
code {{ background: #f4f4f4; padding: 2px 6px; border-radius: 3px; }}
.watermark {{ margin-top: 40px; padding: 16px; background: #f9f9f9; border-left: 4px solid #4a9eff; font-size: 0.9em; color: #555; }}
</style>
</head>
<body>
<h1>QECTOR Code Documentation</h1>
<p><strong>{_html_escape(FULL_VERSION)} — Doc Generator v{_html_escape(DOC_GENERATOR_VERSION)}</strong></p>
<hr>
<h2>Code Summary</h2>
{props}
{analysis_html}
{recs_html}
<div class="watermark">
<strong>Provenance</strong><br>
{provenance_html}
</div>
</body>
</html>"""
# ------------------------------------------------------------------
# LaTeX — every interpolated value passes through latex_escape
# ------------------------------------------------------------------
def _generate_latex(self, code, md: dict, nq: int, nc: int, recs: list[dict]) -> str:
if recs:
rec_rows = "".join(
" & ".join(latex_escape(v) for v in self._rec_display(row)) + r" \\" + "\n"
for row in recs
)
else:
rec_rows = r"(backend unavailable) & n/a & n/a & n/a \\" + "\n"
return (
r"\documentclass{article}" + "\n"
r"\usepackage[utf8]{inputenc}" + "\n"
r"\usepackage{geometry,booktabs,longtable}" + "\n"
r"\geometry{margin=2.5cm}" + "\n"
r"\begin{document}" + "\n"
r"\title{\textbf{QECTOR Code Documentation}}" + "\n"
rf"\author{{{latex_escape(FULL_VERSION)} \\ Doc Generator v{latex_escape(DOC_GENERATOR_VERSION)}}}" + "\n"
r"\date{\today}" + "\n"
r"\maketitle" + "\n"
r"\section*{Code Summary}" + "\n"
r"\begin{tabular}{ll}" + "\n"
rf"Qubits: & {latex_escape(nq)} \\" + "\n"
rf"Checks: & {latex_escape(nc)} \\" + "\n"
rf"Distance: & {latex_escape(md.get('distance', 'N/A'))} \\" + "\n"
rf"Name: & {latex_escape(md.get('name', 'N/A'))} \\" + "\n"
rf"Max qubit degree: & {latex_escape(md.get('max_qubit_degree', 'N/A'))} \\" + "\n"
r"\end{tabular}" + "\n"
r"\section*{Code Analysis}" + "\n"
r"\begin{tabular}{ll}" + "\n"
rf"Rate: & {latex_escape(_rate_str(nq, nc))} \\" + "\n"
rf"Parity Check Matrix: & ${int(nc)}\times{int(nq)}$ \\" + "\n"
r"\end{tabular}" + "\n"
r"\section*{Decoder Recommendations}" + "\n"
rf"Measured on this code ({latex_escape(md.get('name', 'unnamed'))}): "
rf"{RECOMMENDATION_TRIALS} seeded single-shot decodes per decoder at "
rf"$p={RECOMMENDATION_ERROR_RATE}$." + "\n"
r"\begin{longtable}{llll}" + "\n"
r"Decoder & Mean latency & Logical failure fraction & Notes \\" + "\n"
r"\midrule" + "\n"
+ rec_rows
+ r"\end{longtable}" + "\n"
r"\section*{Provenance}" + "\n"
r"\begin{verbatim}" + "\n"
+ _provenance_block() + "\n"
r"\end{verbatim}" + "\n"
r"\end{document}"
)
# ------------------------------------------------------------------
# matplotlib helpers (PDF + SVG)
# ------------------------------------------------------------------
@staticmethod
def _mpl_figure_classes():
"""Import matplotlib without disturbing an already-selected backend.
Only forces the Agg backend when pyplot has not been imported yet;
rendering itself uses explicit Figure/FigureCanvasAgg objects, so no
GUI backend is ever required.
"""
import matplotlib
if "matplotlib.pyplot" not in sys.modules:
try:
matplotlib.use("Agg")
except Exception:
pass
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
return Figure, FigureCanvasAgg
def _tanner_layout(self, code, md: dict) -> tuple[list, list]:
"""Qubit/check coordinates from the backend layout engine."""
if not _HAS_BACKEND:
raise RuntimeError("backend unavailable: cannot compute Tanner graph layout")
family = str(md.get("name", ""))
try:
distance = int(md.get("distance", 0))
except Exception:
distance = 0
return be.get_tanner_graph_layout(code, family, distance)
def _tanner_figure(self, code, md: dict, title: str):
"""Build a rendered Tanner-graph Figure for the given code."""
Figure, FigureCanvasAgg = self._mpl_figure_classes()
from matplotlib.collections import LineCollection
q_coords, c_coords = self._tanner_layout(code, md)
fig = Figure(figsize=(8.0, 6.0), dpi=150)
FigureCanvasAgg(fig)
ax = fig.add_subplot(111)
H = _parity_check_dense(code)
segments = []
if H is not None:
rows, cols = np.nonzero(H)
for r, c in zip(rows.tolist(), cols.tolist()):
if r < len(c_coords) and c < len(q_coords):
segments.append([c_coords[r], q_coords[c]])
if segments:
ax.add_collection(
LineCollection(segments, colors="#9a9a9a", linewidths=0.8, zorder=1)
)
if q_coords:
ax.scatter(
[p[0] for p in q_coords], [p[1] for p in q_coords],
marker="o", s=60, c="#4a9eff", edgecolors="#1a3c6e",
label=f"qubits ({len(q_coords)})", zorder=2,
)
if c_coords:
ax.scatter(
[p[0] for p in c_coords], [p[1] for p in c_coords],
marker="s", s=55, c="#e07a5f", edgecolors="#7a2e1d",
label=f"checks ({len(c_coords)})", zorder=3,
)
ax.set_title(_mpl_text(title), fontsize=11)
ax.set_aspect("equal", adjustable="datalim")
ax.set_xticks([])
ax.set_yticks([])
if q_coords or c_coords:
ax.legend(loc="best", fontsize=8)
fig.tight_layout()
return fig
def _pdf_title_page(self, md: dict, nq: int, nc: int):
Figure, FigureCanvasAgg = self._mpl_figure_classes()
fig = Figure(figsize=(8.27, 11.69), dpi=150)
FigureCanvasAgg(fig)
fig.suptitle("QECTOR Code Documentation", fontsize=20, fontweight="bold", y=0.94)
fig.text(
0.5, 0.90,
_mpl_text(f"{FULL_VERSION} — Doc Generator v{DOC_GENERATOR_VERSION}"),
ha="center", fontsize=10,
)
ax = fig.add_axes([0.12, 0.42, 0.76, 0.42])
ax.axis("off")
rows = [
("Name", md.get("name", "N/A")),
("Qubits", nq),
("Checks", nc),
("Distance", md.get("distance", "N/A")),
("Rate", _rate_str(nq, nc)),
("Max qubit degree", md.get("max_qubit_degree", "N/A")),
]
table = ax.table(
cellText=[[k, _mpl_text(v)] for k, v in rows],
colLabels=["Property", "Value"],
loc="upper center", cellLoc="left", colLoc="left",
)
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1, 1.8)
fig.text(0.12, 0.30, "Provenance", fontsize=12, fontweight="bold")
fig.text(
0.12, 0.29, _mpl_text(_provenance_block()),
fontsize=9, family="monospace", va="top",
)
return fig
def _pdf_recommendations_page(self, md: dict, recs: list[dict]):
Figure, FigureCanvasAgg = self._mpl_figure_classes()
fig = Figure(figsize=(8.27, 11.69), dpi=150)
FigureCanvasAgg(fig)
fig.suptitle("Decoder Recommendations", fontsize=16, fontweight="bold", y=0.94)
fig.text(
0.5, 0.90,
_mpl_text(
f"Measured on this code ({md.get('name', 'unnamed')}): "
f"{RECOMMENDATION_TRIALS} seeded single-shot decodes per decoder "
f"at p={RECOMMENDATION_ERROR_RATE}."
),
ha="center", fontsize=9,
)
ax = fig.add_axes([0.06, 0.40, 0.88, 0.45])
ax.axis("off")
if recs:
cells = []
for row in recs:
decoder, latency, failure, note = self._rec_display(row)
if len(note) > 58:
note = note[:55] + "..."
cells.append([_mpl_text(decoder), _mpl_text(latency),
_mpl_text(failure), _mpl_text(note)])
else:
cells = [["(backend unavailable)", "n/a", "n/a", "n/a"]]
table = ax.table(
cellText=cells,
colLabels=["Decoder", "Mean latency", "Logical failure fraction", "Notes"],
loc="upper center", cellLoc="left", colLoc="left",
colWidths=[0.20, 0.16, 0.24, 0.40],
)
table.auto_set_font_size(False)
table.set_fontsize(8)
table.scale(1, 1.8)
return fig
# ------------------------------------------------------------------
# PDF — genuine multi-page document via matplotlib PdfPages
# ------------------------------------------------------------------
def _generate_pdf(self, code, md: dict, nq: int, nc: int, recs: list[dict], path: Path) -> int:
"""Write a genuine 3-page PDF to ``path``; returns the page count."""
from matplotlib.backends.backend_pdf import PdfPages
name = md.get("name", "code")
with PdfPages(
path,
metadata={
"Title": f"QECTOR Code Documentation — {name}",
"Subject": WATERMARK,
"Creator": f"{FULL_VERSION} Doc Generator v{DOC_GENERATOR_VERSION}",
},
) as pdf:
pdf.savefig(self._pdf_title_page(md, nq, nc))
pdf.savefig(
self._tanner_figure(
code, md,
f"Tanner graph — {name} ({nq} qubits, {nc} checks)",
)
)
pdf.savefig(self._pdf_recommendations_page(md, recs))
pages = pdf.get_pagecount()
if pages < 2:
raise RuntimeError(f"PDF generation produced only {pages} page(s)")
return pages
# ------------------------------------------------------------------
# SVG — standalone Tanner graph with the document title embedded
# ------------------------------------------------------------------
def _generate_svg(self, code, md: dict, path: Path) -> None:
name = md.get("name", "code")
title = f"QECTOR Code Documentation — {name} Tanner graph"
fig = self._tanner_figure(code, md, title)
fig.savefig(
path,
format="svg",
metadata={
"Title": title,
"Creator": f"{FULL_VERSION} Doc Generator v{DOC_GENERATOR_VERSION}",
"Description": WATERMARK,
},
)