Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/dependabot.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ updates:
- dependency-name: pytest
- dependency-name: sinter
- dependency-name: pybind11-stubgen
- dependency-name: jupytext
schedule:
interval: "monthly"
versioning-strategy: "increase-if-necessary"
Expand Down
39 changes: 39 additions & 0 deletions docs/BUILD
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

load("@rules_python//python:py_binary.bzl", "py_binary")
load("@rules_python//python:py_test.bzl", "py_test")

TUTORIAL_FILES = glob([
"tutorial.ipynb",
]) + glob(
["tutorial.py"],
allow_empty = True,
)

py_binary(
name = "sync_tutorial_notebook",
srcs = ["sync_tutorial_notebook.py"],
data = TUTORIAL_FILES,
deps = ["@pypi//jupytext"],
)

py_test(
name = "tutorial_jupytext_sync_test",
srcs = ["sync_tutorial_notebook.py"],
args = ["--check"],
data = TUTORIAL_FILES,
main = "sync_tutorial_notebook.py",
deps = ["@pypi//jupytext"],
)
143 changes: 143 additions & 0 deletions docs/sync_tutorial_notebook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Synchronizes the paired Jupytext tutorial notebook."""

import argparse
import difflib
import json
import os
from pathlib import Path
import shutil
import sys
import tempfile

from jupytext.cli import jupytext

FORMATS = "ipynb,py:percent"
NOTEBOOK_PATH = Path("docs/tutorial.ipynb")
SOURCE_PATH = Path("docs/tutorial.py")


def _run_jupytext(args: list[str], cwd: Path) -> None:
old_cwd = Path.cwd()
try:
os.chdir(cwd)
exit_code = jupytext(args)
except SystemExit as ex:
exit_code = ex.code if isinstance(ex.code, int) else 1
finally:
os.chdir(old_cwd)

if exit_code:
raise RuntimeError(f"jupytext failed with exit code {exit_code}: {' '.join(args)}")


def _write_notebook_from_source(root: Path) -> None:
if not (root / SOURCE_PATH).exists():
_run_jupytext(
[
str(NOTEBOOK_PATH),
"--set-formats",
FORMATS,
"--quiet",
],
root,
)
return

_run_jupytext(
[
str(SOURCE_PATH),
"--to",
"ipynb",
"--update",
"--output",
str(NOTEBOOK_PATH),
"--quiet",
],
root,
)


def _canonical_json(path: Path) -> list[str]:
return json.dumps(
json.loads(path.read_text()),
indent=2,
sort_keys=True,
).splitlines(keepends=True)


def _check_pair() -> int:
docs_dir = Path(__file__).resolve().parent
source = docs_dir / SOURCE_PATH.name
notebook = docs_dir / NOTEBOOK_PATH.name

if not source.exists():
sys.stderr.write(f"{SOURCE_PATH} is missing; run `bazel run //docs:sync_tutorial_notebook -- --write`.\n")
return 1

with tempfile.TemporaryDirectory() as tmp:
tmp_root = Path(tmp)
tmp_docs = tmp_root / "docs"
tmp_docs.mkdir()
shutil.copy2(source, tmp_docs / SOURCE_PATH.name)
shutil.copy2(notebook, tmp_docs / NOTEBOOK_PATH.name)

_write_notebook_from_source(tmp_root)

expected = _canonical_json(notebook)
actual = _canonical_json(tmp_docs / NOTEBOOK_PATH.name)
if expected != actual:
sys.stderr.write(
f"{NOTEBOOK_PATH} is not synchronized with {SOURCE_PATH}. "
"Run `bazel run //docs:sync_tutorial_notebook -- --write`.\n"
)
sys.stderr.writelines(
difflib.unified_diff(
expected,
actual,
fromfile=str(NOTEBOOK_PATH),
tofile="generated tutorial.ipynb",
)
)
return 1

return 0


def _write_pair() -> int:
workspace = os.environ.get("BUILD_WORKSPACE_DIRECTORY")
if not workspace:
sys.stderr.write("--write must be run with `bazel run //docs:sync_tutorial_notebook -- --write`.\n")
return 1

_write_notebook_from_source(Path(workspace))
return 0


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--check", action="store_true", help="Check that the paired tutorial files are synchronized.")
mode.add_argument("--write", action="store_true", help="Synchronize docs/tutorial.ipynb from docs/tutorial.py.")
args = parser.parse_args()

if args.write:
return _write_pair()
return _check_pair()


if __name__ == "__main__":
sys.exit(main())
17 changes: 13 additions & 4 deletions docs/tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,8 @@
" 'num_errors': num_errors,\n",
" 'num_shots': len(dets),\n",
" 'time_seconds': end_time - start_time,\n",
" }\n"
" }\n",
"\n"
]
},
{
Expand Down Expand Up @@ -1032,7 +1033,8 @@
" bits = body.strip().split()\n",
" row = [int(b) for b in bits]\n",
" rows.append(row)\n",
" return np.array(rows, dtype=np.uint8)\n"
" return np.array(rows, dtype=np.uint8)\n",
"\n"
]
},
{
Expand Down Expand Up @@ -1403,6 +1405,7 @@
"base_uri": "https://localhost:8080/"
},
"id": "ZNKaqvN8dE-X",
"lines_to_next_cell": 2,
"outputId": "34ccf8b2-a1fc-4f1c-e1d9-1ef3f99d594e"
},
"outputs": [
Expand All @@ -1412,12 +1415,14 @@
"text": [
" % Total % Received % Xferd Average Speed Time Time Time Current\n",
" Dload Upload Total Spent Left Speed\n",
"\r 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\r100 44154 100 44154 0 0 238k 0 --:--:-- --:--:-- --:--:-- 239k\n"
"\r",
" 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\r",
"100 44154 100 44154 0 0 238k 0 --:--:-- --:--:-- --:--:-- 239k\n"
]
}
],
"source": [
"!curl 'https://raw.githubusercontent.com/quantumlib/tesseract-decoder/refs/heads/main/testdata/colorcodes/r%3D9%2Cd%3D9%2Cp%3D0.002%2Cnoise%3Dsi1000%2Cc%3Dsuperdense_color_code_X%2Cq%3D121%2Cgates%3Dcz.stim' > d9r9colorcode_p002.stim\n"
"!curl 'https://raw.githubusercontent.com/quantumlib/tesseract-decoder/refs/heads/main/testdata/colorcodes/r%3D9%2Cd%3D9%2Cp%3D0.002%2Cnoise%3Dsi1000%2Cc%3Dsuperdense_color_code_X%2Cq%3D121%2Cgates%3Dcz.stim' > d9r9colorcode_p002.stim"
]
},
{
Expand Down Expand Up @@ -1620,6 +1625,10 @@
"colab": {
"provenance": []
},
"jupytext": {
"formats": "ipynb,py:percent",
"main_language": "python"
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
Expand Down
Loading
Loading