{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Using a QECX file\n", "\n", "QECX is an open format for describing and exchanging implementations of quantum error-correcting codes. A QECX file holds the algebraic definition of the code itself, declarations of the qubit and classical registers, the circuits for each gadget (the steps of an error-corrected computation, such as state preparation, syndrome measurement and logical gates), often in several variants, the error-correction cycles built from them, and the information decoders need. Compilers, simulators, decoders and resource estimators can all work from the same file.\n", "\n", "This tutorial is for those who use an existing QECX file. It loads a file, shows what it contains and how to access each part from Python, checks it, and switches to another code. The running example is the triangular 4.8.8 color code at distance 3, one of the example files distributed with the package. Writing a file of your own is covered in the tutorial *Authoring a QECX file*.\n", "\n", "To run this tutorial as a notebook, install the package with its `viewer` extra, which adds the libraries for drawing circuits and layouts, in an environment with Jupyter:\n", "\n", "```bash\n", "pip install \"python-qecx[viewer]\"\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "1", "metadata": {}, "outputs": [], "source": [ "from qecx import QECXDocument, examples" ] }, { "cell_type": "markdown", "id": "2", "metadata": {}, "source": [ "## Loading and viewing a file\n", "\n", "`QECXDocument.load` reads a QECX file into a document, a Python object whose parts mirror the sections of the file. The function `examples.path` returns the path of an example file distributed with the package. Loading also validates the file: it raises an error if the file breaks the format's rules, and reports less serious findings as warnings." ] }, { "cell_type": "code", "execution_count": null, "id": "3", "metadata": {}, "outputs": [], "source": [ "doc = QECXDocument.load(examples.path(\"color_488_d3.qecx\"))" ] }, { "cell_type": "markdown", "id": "4", "metadata": {}, "source": [ "In a Jupyter notebook, a document displays as an interactive view of its contents, with each section unfolding on a click. Here the circuits are drawn with Matplotlib; by default, the view chooses between drawn and text circuits depending on their size." ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "doc.view(circuit_mode=\"mpl\")" ] }, { "cell_type": "markdown", "id": "6", "metadata": {}, "source": [ "The same overview is available as plain text, for a terminal or a log:" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "doc.view().summary()" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "## What a file contains\n", "\n", "Each section of a QECX file provides information that tools working with the code need. The subsections below show how to read them." ] }, { "cell_type": "markdown", "id": "9", "metadata": {}, "source": [ "### Code\n", "\n", "The algebraic definition identifies the code and gives its parameters [[n, k, d]]: n data qubits encode k logical qubits at distance d. For a CSS code such as this one, the checks are given by two parity-check matrices, `H_X` for the X-type checks and `H_Z` for the Z-type checks, with one row per check and one column per data qubit. Syndrome decoders interpret measured syndromes in terms of these checks." ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "code = doc.code_data\n", "print(doc.code_name, doc.code_type, f\"[[{code.n},{code.k},{code.d}]]\")\n", "print(code.H_X)" ] }, { "cell_type": "markdown", "id": "11", "metadata": {}, "source": [ "The checks and the logical X and Z operators are also available as Pauli strings, one character per data qubit:" ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "print(*code.stabilizer_generators)\n", "print(*code.logical_operators_X, *code.logical_operators_Z)" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "### Registers\n", "\n", "The register template declares the registers that every code block, an encoded copy of the code, carries: the data register with its n qubits, and the ancilla registers, each with a size and, optionally, a purpose. Here there are three ancillas for syndrome measurement. A compiler uses the template to allocate the qubits of each code block, and the circuits of the gadgets declare which of these registers they use." ] }, { "cell_type": "code", "execution_count": null, "id": "14", "metadata": {}, "outputs": [], "source": [ "block = doc.register_template.per_code_block\n", "for register in [block.data_qreg, *block.ancilla_qregs.values()]:\n", " print(register.name, register.size, register.purpose.value)" ] }, { "cell_type": "markdown", "id": "15", "metadata": {}, "source": [ "The number of qubits a gadget acts on also depends on its variant: Steane-type and Knill-type syndrome measurements need further ancilla qubits, which their circuits allocate themselves." ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "{name: variant.circuit.num_qubits for name, variant in doc.syndrome_measurements.items()}" ] }, { "cell_type": "markdown", "id": "17", "metadata": {}, "source": [ "### Qubit layout\n", "\n", "The optional qubit layout describes how the qubits of a code block are arranged. Foremost it gives the topology, as a cell complex of vertices, edges and faces on which the registers are placed. It can also give the geometry, an embedding of that structure in space. Here the data qubits sit on the vertices and one syndrome ancilla on each face, and every face carries a color, stored as an integer. Compilers can use the layout for placement and routing, and decoders such as Chromobius take the face colors from it." ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": {}, "outputs": [], "source": [ "fig, ax = doc.view().draw_layout()" ] }, { "cell_type": "markdown", "id": "19", "metadata": {}, "source": [ "### Gadgets\n", "\n", "The operations section holds the gadgets, grouped by operation type: state preparation, reset, data measurement, logical gates, logical measurement and syndrome measurement. An operation can come in several variants, alternative implementations of the same operation, one of which is its default. A compiler picks a variant for each logical operation and translates the operation into it." ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "print(\"state preparation:\", {state: list(group) for state, group in doc.state_preparations.items()})\n", "print(\"reset:\", {state: list(group) for state, group in doc.resets.items()})\n", "print(\"data measurement:\", {basis.value: list(group) for basis, group in doc.data_measurements.items()})\n", "print(\"logical gates:\", list(doc.logical_gates))\n", "print(\"logical measurement:\", [str(observable) for observable in doc.logical_measurements])\n", "print(\"syndrome measurement:\", list(doc.syndrome_measurements))" ] }, { "cell_type": "markdown", "id": "21", "metadata": {}, "source": [ "A variant holds its circuit as a Qiskit `QuantumCircuit`, ready to draw, simulate or transpile, together with the information that connects the circuit to the rest of the file. Here is the default circuit that prepares the logical state |0⟩, with its name and whether it is fault-tolerant:" ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "preparation = doc.state_preparations[\"0\"].default\n", "print(preparation.name, preparation.fault_tolerant)\n", "preparation.circuit.draw(\"mpl\")" ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "Besides the circuit, a variant declares how the circuit's registers relate to the rest of the file. Each register either refers to an entry of the register template, such as the data register of the code block, or is allocated by the gadget itself, such as the classical registers that receive measurement results. Readout declarations state what these results mean: for the sequential syndrome measurement, which register holds the outcomes of the Z checks and which those of the X checks. A compiler uses the register declarations to place the circuit on the qubits of a code block, and a decoder uses the readout declarations to interpret every measured bit." ] }, { "cell_type": "code", "execution_count": null, "id": "24", "metadata": {}, "outputs": [], "source": [ "from qecx import DynamicRegisterDecl, InheritedRegisterDecl\n", "\n", "sequential = doc.syndrome_measurements[\"sequential\"]\n", "for register, declaration in sequential.registers.items():\n", " if isinstance(declaration, InheritedRegisterDecl):\n", " print(f\"{register.name}: template entry {declaration.target.name}\")\n", " elif isinstance(declaration, DynamicRegisterDecl):\n", " print(f\"{register.name}: allocated by the variant, scope {declaration.scope.value}, size {declaration.size}\")\n", "for readout in sequential.syndrome_cregs:\n", " print(f\"{readout.name}: outcomes of the checks in {readout.source}\")" ] }, { "cell_type": "markdown", "id": "25", "metadata": {}, "source": [ "### Variants compared\n", "\n", "Variants of one gadget can differ considerably. The file contains two syndrome measurement circuits that use the same three ancillas. The `sequential` variant measures one check after another, first the Z checks, then the X checks." ] }, { "cell_type": "code", "execution_count": null, "id": "26", "metadata": {}, "outputs": [], "source": [ "doc.syndrome_measurements[\"sequential\"].circuit.draw(\"mpl\", justify=\"none\", fold=-1, scale=0.6)" ] }, { "cell_type": "markdown", "id": "27", "metadata": {}, "source": [ "The `parallel` variant follows the schedule of Landahl, Anderson and Rice, which it cites from the file's references. It measures the X checks first, then the Z checks, and interleaves the checks of each type so that several act in the same time step; each barrier closes one time step. Its depth stays almost constant as the distance grows, while the sequential depth increases. Their depths, sequential first and with barriers adding no layer of their own, are 22 and 20 at distance 3, 38 and 22 at distance 5, and 54 and 22 at distance 7. Which variant works better depends on the hardware." ] }, { "cell_type": "code", "execution_count": null, "id": "28", "metadata": {}, "outputs": [], "source": [ "parallel = doc.syndrome_measurements[\"parallel\"]\n", "print([reference.title for reference in parallel.references])\n", "parallel.circuit.draw(\"mpl\", fold=-1, scale=0.6)" ] }, { "cell_type": "markdown", "id": "29", "metadata": {}, "source": [ "### Cycles\n", "\n", "The error-correction cycles combine syndrome measurements into rounds. Each cycle lists its steps, and each step names a syndrome measurement variant and how many times it repeats. A compiler inserts these cycles between the logical operations. A repeat count can refer to a value elsewhere in the file instead of stating a number: `ScalarRef(path='code.d')` repeats the measurement as many times as the code distance, here three times." ] }, { "cell_type": "code", "execution_count": null, "id": "30", "metadata": {}, "outputs": [], "source": [ "for name, cycle in doc.error_correction_cycles.items():\n", " print(name, [(step.measurement.name, step.repeat) for step in cycle.steps])" ] }, { "cell_type": "markdown", "id": "31", "metadata": {}, "source": [ "### Decoders\n", "\n", "The optional decoder configuration lists the syndrome decoders the implementation supports, with any extra information each needs. Tesseract needs no further information, while Chromobius needs a color for every check, given in its `color` tag." ] }, { "cell_type": "code", "execution_count": null, "id": "32", "metadata": {}, "outputs": [], "source": [ "for slug, decoder in doc.decoder_config.items():\n", " print(slug, [tag.name for tag in decoder.tags])" ] }, { "cell_type": "markdown", "id": "33", "metadata": {}, "source": [ "The `color` tag does not repeat the colors. It refers to the face colors of the qubit layout:" ] }, { "cell_type": "code", "execution_count": null, "id": "34", "metadata": {}, "outputs": [], "source": [ "color = doc.decoder_config[\"chromobius\"].tags[0]\n", "print(color.by_source[\"H_X\"])\n", "print([face.color for face in doc.qubit_layout.cell_complex.faces])" ] }, { "cell_type": "markdown", "id": "35", "metadata": {}, "source": [ "### Properties\n", "\n", "The properties record the file's metadata, such as its author, license and references. Individual variants cite these references, as the `parallel` syndrome measurement above does." ] }, { "cell_type": "code", "execution_count": null, "id": "36", "metadata": {}, "outputs": [], "source": [ "print(doc.properties.author, doc.properties.license)\n", "for reference in doc.references:\n", " credit = f\"{reference.authors} ({reference.year})\" if reference.authors else reference.url\n", " print(f\"{credit}: {reference.title}\")" ] }, { "cell_type": "markdown", "id": "37", "metadata": {}, "source": [ "## Checking a file\n", "\n", "`validate()` checks the document against every rule of the format and returns the findings; an empty tuple means the document is valid. Loading has already validated this file, so an explicit check is mainly useful after changing a document." ] }, { "cell_type": "code", "execution_count": null, "id": "38", "metadata": {}, "outputs": [], "source": [ "doc.validate()" ] }, { "cell_type": "markdown", "id": "39", "metadata": {}, "source": [ "The command-line tool runs the same check without Python:\n", "\n", "```bash\n", "qecx color_488_d3.qecx --validate\n", "```" ] }, { "cell_type": "markdown", "id": "40", "metadata": {}, "source": [ "## Switching codes\n", "\n", "Other files are read the same way. These are the example files distributed with the package, with their parameters and syndrome measurement variants:" ] }, { "cell_type": "code", "execution_count": null, "id": "41", "metadata": {}, "outputs": [], "source": [ "for name in examples.names():\n", " other = QECXDocument.load(examples.path(name))\n", " n, k, d = other.code_data.n, other.code_data.k, other.code_data.d\n", " print(f\"{name}: {other.code_name} [[{n},{k},{d}]]\", list(other.syndrome_measurements))" ] }, { "cell_type": "markdown", "id": "42", "metadata": {}, "source": [ "A larger code loads the same way, here the 4.8.8 color code at distance 7, stored as a ZIP archive, the container QECX uses for large files. Its circuits are long, so the view below leaves out the circuit diagrams with `circuit_mode=\"none\"`; it still shows the layout, the matrices and the OpenQASM source of every variant." ] }, { "cell_type": "code", "execution_count": null, "id": "43", "metadata": {}, "outputs": [], "source": [ "doc = QECXDocument.load(examples.path(\"color_488_d7.qecx\"))\n", "doc.view(circuit_mode=\"none\")" ] }, { "cell_type": "markdown", "id": "44", "metadata": {}, "source": [ "## Next steps\n", "\n", "- The tutorial [Authoring a QECX file](authoring_qecx_files.ipynb) shows how to write a file and how to edit an existing one.\n", "- The [API reference](../api/index.md) documents every class and method.\n", "- The [format specification](../format_specification.md) defines every field of a QECX file." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.13" } }, "nbformat": 4, "nbformat_minor": 5 }