{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Authoring a QECX file\n", "\n", "This tutorial shows how to write a QECX file with the `qecx` package. It builds the triangular 4.8.8 color code at distance 3, the running example of the tutorial [Using a QECX file](using_qecx_files.ipynb), section by section, then validates and saves it. It also covers editing an existing file, repairing a file that does not validate, and codes with more than one logical qubit.\n", "\n", "To run this tutorial as a notebook, install the package with its `viewer` extra in an environment with Jupyter:\n", "\n", "```bash\n", "pip install \"python-qecx[viewer]\"\n", "```" ] }, { "cell_type": "markdown", "id": "1", "metadata": {}, "source": [ "The tutorial writes its files to a temporary directory, which the last cell removes." ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": {}, "outputs": [], "source": [ "import json\n", "import shutil\n", "import tempfile\n", "import zipfile\n", "from dataclasses import replace\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister\n", "\n", "from qecx import (\n", " CellComplex,\n", " CellPlacement,\n", " CellType,\n", " CSSCodeData,\n", " DataMeasurementVariant,\n", " DecoderTag,\n", " DynamicRegisterDecl,\n", " ECCycleStep,\n", " Embedding,\n", " Face,\n", " InheritedRegisterDecl,\n", " LogicalGateVariant,\n", " MeasurementBasis,\n", " Operand,\n", " PauliProductOperator,\n", " Properties,\n", " QECXAuthoringError,\n", " QECXDocument,\n", " QECXValidationFailedError,\n", " QubitLayout,\n", " Reference,\n", " RegisterPurpose,\n", " RegisterScope,\n", " RegisterTemplateEntry,\n", " StatePreparationVariant,\n", " SyndromeCregDecl,\n", " SyndromeMeasurementVariant,\n", " SyndromeSource,\n", " TransversalReadoutCregDecl,\n", " qecx_creator,\n", " ref,\n", ")\n", "\n", "WORKDIR = Path(tempfile.mkdtemp(prefix=\"qecx_authoring_\"))" ] }, { "cell_type": "markdown", "id": "3", "metadata": {}, "source": [ "## Building a document\n", "\n", "A document starts from the code and is built up section by section. Because a section can only refer to what the document already contains, the subsections below follow that order. To prevent the document being left in a corrupted state, each method call either applies completely or raises a `QECXAuthoringError` and leaves the document unchanged." ] }, { "cell_type": "markdown", "id": "4", "metadata": {}, "source": [ "### Code\n", "\n", "The code section is built from a code description for the code's family, here `CSSCodeData` for a CSS code. It takes the parameters [[7, 1, 3]], the parity-check matrices and the logical operators. The 4.8.8 color code is self-dual, so `H_X` and `H_Z` are equal, with one row per face. Pauli strings are given with qubit 0 first (`from_big_endian`). The document is created from the code and a descriptive name." ] }, { "cell_type": "code", "execution_count": null, "id": "5", "metadata": {}, "outputs": [], "source": [ "H = np.array([\n", " [0, 1, 1, 1, 1, 0, 0],\n", " [1, 1, 0, 1, 0, 1, 0],\n", " [0, 0, 0, 1, 1, 1, 1],\n", "], dtype=np.uint8)\n", "\n", "code = CSSCodeData(\n", " n=7, k=1, d=3,\n", " H_X=H,\n", " H_Z=H,\n", " logical_operators_X=(PauliProductOperator.from_big_endian(\"XXXIIII\"),),\n", " logical_operators_Z=(PauliProductOperator.from_big_endian(\"ZZZIIII\"),),\n", ")\n", "doc = QECXDocument(code, code_name=\"Distance-3 Triangular 4.8.8 Color Code\")" ] }, { "cell_type": "markdown", "id": "6", "metadata": {}, "source": [ "`missing()` lists what a complete document still needs. A document can be incomplete while it is being built, but it can only be saved once the list is empty:" ] }, { "cell_type": "code", "execution_count": null, "id": "7", "metadata": {}, "outputs": [], "source": [ "for finding in doc.missing():\n", " print(finding.message)" ] }, { "cell_type": "markdown", "id": "8", "metadata": {}, "source": [ "### References\n", "\n", "References can be added in two ways: explicitly with `add_reference`, or implicitly when a variant that cites them is added. The bibliography keeps the order in which references are added, and by convention the first one is the reference that defines the code. The paper by Bombín and Martín-Delgado that introduced color codes is therefore added here first; the source of the parallel syndrome measurement schedule is added later, together with the variant that cites it. Every `add_*` method except `add_operation` accepts either the object itself or its fields as keyword arguments; the reference is added here in the keyword form, the register template entry below in the object form." ] }, { "cell_type": "code", "execution_count": null, "id": "9", "metadata": {}, "outputs": [], "source": [ "bombin = doc.add_reference(\n", " key=\"bombin_martin_delgado_2006\",\n", " title=\"Topological quantum distillation\",\n", " authors=\"H. Bombín and M. A. Martín-Delgado\",\n", " year=2006,\n", " doi=\"10.1103/PhysRevLett.97.180501\",\n", " arxiv=\"quant-ph/0605138\",\n", " note=\"Defines the color code family (primary reference)\",\n", ")" ] }, { "cell_type": "markdown", "id": "10", "metadata": {}, "source": [ "### Registers\n", "\n", "The register template entry for the data register, `data_qreg`, is created automatically from n. The ancilla register `syndrome`, with one ancilla qubit per face, is added here in the object form:" ] }, { "cell_type": "code", "execution_count": null, "id": "11", "metadata": {}, "outputs": [], "source": [ "print(doc.data_qreg)\n", "\n", "syndrome = doc.add_ancilla_register_template(\n", " RegisterTemplateEntry(\"syndrome\", 3, RegisterPurpose.SYNDROME))\n", "print(syndrome)" ] }, { "cell_type": "markdown", "id": "12", "metadata": {}, "source": [ "The circuits use Qiskit registers of the same sizes. `emit_data_register()` and `emit_ancilla_register(\"syndrome\")` create such registers, named after the template entries; Qiskit registers can also be created directly, as here, with names of one's choice. A variant binds each circuit register with a declaration: `InheritedRegisterDecl` for a register from the template, and `DynamicRegisterDecl` for a register the gadget allocates itself, such as a classical register for its measurement results." ] }, { "cell_type": "code", "execution_count": null, "id": "13", "metadata": {}, "outputs": [], "source": [ "q_data = QuantumRegister(code.n, \"q_data\")\n", "a_syndrome = QuantumRegister(syndrome.size, \"a_syndrome\")\n", "\n", "data_decl = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg)\n", "syndrome_decl = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=syndrome)\n", "syndrome_bits_decl = DynamicRegisterDecl(scope=RegisterScope.OUTPUT, size=3, purpose=RegisterPurpose.SYNDROME)" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "### Gadgets\n", "\n", "Each gadget is added as a variant: an object that holds the circuit, the register declarations and whether the circuit is fault-tolerant. `add_operation` files it under its operation, given by the variant's class and its key fields, such as the prepared state or the gate. The first variant of an operation becomes its default; another variant can be made the default when it is added (`make_default=True`) or later with `set_default`. `missing()` shrinks as the required operations are added." ] }, { "cell_type": "markdown", "id": "15", "metadata": {}, "source": [ "#### State preparation\n", "\n", "The logical state |0⟩ is prepared by a canonical encoding circuit for CSS codes: Hadamard gates on three qubits, followed by CNOT gates. The circuit is not fault-tolerant." ] }, { "cell_type": "code", "execution_count": null, "id": "16", "metadata": {}, "outputs": [], "source": [ "encoder = QuantumCircuit(q_data)\n", "for qubit in [0, 1, 3]:\n", " encoder.h(q_data[qubit])\n", "for control, target in [(0, 2), (0, 4), (0, 5), (1, 2), (1, 5), (1, 6), (3, 4), (3, 5), (3, 6)]:\n", " encoder.cx(q_data[control], q_data[target])\n", "encoder.draw(\"mpl\")" ] }, { "cell_type": "code", "execution_count": null, "id": "17", "metadata": {}, "outputs": [], "source": [ "doc.add_operation(StatePreparationVariant(\n", " name=\"css_encoder\",\n", " state=\"0\",\n", " circuit=encoder,\n", " registers={q_data: data_decl},\n", " fault_tolerant=False,\n", " description=\"Encoding circuit for the logical state |0⟩.\",\n", "))\n", "\n", "for finding in doc.missing():\n", " print(finding.message)" ] }, { "cell_type": "markdown", "id": "18", "metadata": {}, "source": [ "#### Syndrome measurement, sequential\n", "\n", "The sequential variant measures one check after another: first the three Z checks, then, after a barrier, the three X checks. The ancilla of a face serves both of its checks. Two output registers receive the outcomes, and `syndrome_cregs` declares which of them holds the outcomes of the Z checks and which those of the X checks, so that a syndrome decoder can interpret them." ] }, { "cell_type": "code", "execution_count": null, "id": "19", "metadata": {}, "outputs": [], "source": [ "# Data qubits of each check in CNOT order; the same faces carry the Z and the X checks.\n", "check_order = [[1, 2, 3, 4], [0, 1, 3, 5], [3, 4, 5, 6]]\n", "\n", "c_z_syndrome = ClassicalRegister(3, \"c_z_syndrome\")\n", "c_x_syndrome = ClassicalRegister(3, \"c_x_syndrome\")\n", "circuit = QuantumCircuit(q_data, a_syndrome, c_z_syndrome, c_x_syndrome)\n", "for check, qubits in enumerate(check_order):\n", " circuit.reset(a_syndrome[check])\n", " for qubit in qubits:\n", " circuit.cx(q_data[qubit], a_syndrome[check])\n", " circuit.measure(a_syndrome[check], c_z_syndrome[check])\n", "circuit.barrier(q_data, a_syndrome)\n", "for check, qubits in enumerate(check_order):\n", " circuit.reset(a_syndrome[check])\n", " circuit.h(a_syndrome[check])\n", " for qubit in qubits:\n", " circuit.cx(a_syndrome[check], q_data[qubit])\n", " circuit.h(a_syndrome[check])\n", " circuit.measure(a_syndrome[check], c_x_syndrome[check])\n", "\n", "circuit.draw(\"mpl\", fold=-1)" ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "sequential = SyndromeMeasurementVariant(\n", " name=\"sequential\",\n", " circuit=circuit,\n", " registers={\n", " q_data: data_decl,\n", " a_syndrome: syndrome_decl,\n", " c_z_syndrome: syndrome_bits_decl,\n", " c_x_syndrome: syndrome_bits_decl,\n", " },\n", " syndrome_cregs=(\n", " SyndromeCregDecl(name=\"c_z_syndrome\", source=SyndromeSource.H_Z),\n", " SyndromeCregDecl(name=\"c_x_syndrome\", source=SyndromeSource.H_X),\n", " ),\n", " fault_tolerant=False,\n", " description=\"Z checks, then X checks, one check at a time.\",\n", ")\n", "doc.add_operation(sequential)\n", "\n", "for finding in doc.missing():\n", " print(finding.message)" ] }, { "cell_type": "markdown", "id": "21", "metadata": {}, "source": [ "#### Syndrome measurement, parallel\n", "\n", "The parallel variant follows the schedule of Landahl, Anderson and Rice: all ancillas work at the same time, first on the X checks, then on the Z checks, in eight time steps per round, each closed by a barrier. At distance 3 the fifth step is empty. The variant cites the paper that describes the schedule, and the reference is added to the document together with the variant." ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "# One row per time step: check (ancilla) -> data qubit it couples to in that step.\n", "schedule = [\n", " {0: 3, 2: 5},\n", " {0: 4, 2: 6},\n", " {0: 1, 2: 3},\n", " {0: 2, 1: 5, 2: 4},\n", " {},\n", " {1: 3},\n", " {1: 0},\n", " {1: 1},\n", "]\n", "\n", "circuit = QuantumCircuit(q_data, a_syndrome, c_x_syndrome, c_z_syndrome)\n", "circuit.reset(a_syndrome)\n", "circuit.h(a_syndrome)\n", "circuit.barrier(q_data, a_syndrome)\n", "for step in schedule:\n", " for check, qubit in step.items():\n", " circuit.cx(a_syndrome[check], q_data[qubit])\n", " circuit.barrier(q_data, a_syndrome)\n", "circuit.h(a_syndrome)\n", "circuit.measure(a_syndrome, c_x_syndrome)\n", "circuit.reset(a_syndrome)\n", "circuit.barrier(q_data, a_syndrome)\n", "for step in schedule:\n", " for check, qubit in step.items():\n", " circuit.cx(q_data[qubit], a_syndrome[check])\n", " circuit.barrier(q_data, a_syndrome)\n", "circuit.measure(a_syndrome, c_z_syndrome)\n", "\n", "circuit.draw(\"mpl\", fold=-1)" ] }, { "cell_type": "code", "execution_count": null, "id": "23", "metadata": {}, "outputs": [], "source": [ "landahl = Reference(\n", " key=\"landahl_anderson_rice_2011\",\n", " title=\"Fault-tolerant quantum computing with color codes\",\n", " authors=\"A. J. Landahl, J. T. Anderson, and P. R. Rice\",\n", " year=2011,\n", " arxiv=\"1108.5738\",\n", " note=\"Locality-respecting syndrome schedule used by syndrome_measurement.parallel\",\n", ")\n", "parallel = SyndromeMeasurementVariant(\n", " name=\"parallel\",\n", " circuit=circuit,\n", " registers={\n", " q_data: data_decl,\n", " a_syndrome: syndrome_decl,\n", " c_x_syndrome: syndrome_bits_decl,\n", " c_z_syndrome: syndrome_bits_decl,\n", " },\n", " syndrome_cregs=(\n", " SyndromeCregDecl(name=\"c_x_syndrome\", source=SyndromeSource.H_X),\n", " SyndromeCregDecl(name=\"c_z_syndrome\", source=SyndromeSource.H_Z),\n", " ),\n", " fault_tolerant=False,\n", " description=\"X checks, then Z checks, after the schedule of Landahl, Anderson and Rice.\",\n", " references=(landahl,),\n", ")\n", "doc.add_operation(parallel)\n", "print(list(doc.syndrome_measurements), \"default:\", doc.syndrome_measurements.default.name)" ] }, { "cell_type": "markdown", "id": "24", "metadata": {}, "source": [ "#### Logical gates\n", "\n", "The code is self-dual, so a Hadamard gate on every data qubit acts as a logical Hadamard gate. A logical gate names the gate and its operands: here a single operand, code block 0, with all of its logical qubits (`logical_qubit=None`). The `block_index` in the register declaration states which code block the register belongs to." ] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [ "circuit = QuantumCircuit(q_data)\n", "circuit.h(q_data)\n", "\n", "doc.add_operation(LogicalGateVariant(\n", " name=\"transversal\",\n", " gate=\"h\",\n", " operands=(Operand(block=0, logical_qubit=None),),\n", " circuit=circuit,\n", " registers={q_data: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=0)},\n", " fault_tolerant=True,\n", " description=\"Hadamard gate on every data qubit.\",\n", " references=(bombin,),\n", "))\n", "\n", "for finding in doc.missing():\n", " print(finding.message)" ] }, { "cell_type": "markdown", "id": "26", "metadata": {}, "source": [ "The transversal CNOT gate acts on two code blocks, with a control and a target operand. The two data registers are told apart by their `block_index`." ] }, { "cell_type": "code", "execution_count": null, "id": "27", "metadata": {}, "outputs": [], "source": [ "q_data_ctrl = QuantumRegister(code.n, \"q_data_ctrl\")\n", "q_data_tgt = QuantumRegister(code.n, \"q_data_tgt\")\n", "circuit = QuantumCircuit(q_data_ctrl, q_data_tgt)\n", "circuit.cx(q_data_ctrl, q_data_tgt)\n", "\n", "doc.add_operation(LogicalGateVariant(\n", " name=\"transversal\",\n", " gate=\"cx\",\n", " operands=(\n", " Operand(block=0, logical_qubit=None, role=\"control\"),\n", " Operand(block=1, logical_qubit=None, role=\"target\"),\n", " ),\n", " circuit=circuit,\n", " registers={\n", " q_data_ctrl: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=0),\n", " q_data_tgt: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=1),\n", " },\n", " fault_tolerant=True,\n", " description=\"CNOT gates between corresponding data qubits of two code blocks.\",\n", "))\n", "print(sorted(doc.logical_gates))" ] }, { "cell_type": "markdown", "id": "28", "metadata": {}, "source": [ "#### Data measurement\n", "\n", "Measuring every data qubit in the Z basis gives the value of the logical Z operator, read from the register named by `result_creg`. The same bits also determine the values of the Z checks; `transversal_readout_cregs` declares this for a syndrome decoder." ] }, { "cell_type": "code", "execution_count": null, "id": "29", "metadata": {}, "outputs": [], "source": [ "c_data_meas = ClassicalRegister(code.n, \"c_data_meas\")\n", "circuit = QuantumCircuit(q_data, c_data_meas)\n", "circuit.measure(q_data, c_data_meas)\n", "\n", "doc.add_operation(DataMeasurementVariant(\n", " name=\"direct\",\n", " basis=MeasurementBasis.Z,\n", " circuit=circuit,\n", " result_creg=c_data_meas,\n", " registers={\n", " q_data: data_decl,\n", " c_data_meas: DynamicRegisterDecl(\n", " scope=RegisterScope.OUTPUT, size=code.n, purpose=RegisterPurpose.LOGICAL_DATA),\n", " },\n", " transversal_readout_cregs=(TransversalReadoutCregDecl(name=\"c_data_meas\", source=SyndromeSource.H_Z),),\n", " fault_tolerant=True,\n", " description=\"Z-basis measurement of every data qubit.\",\n", "))\n", "\n", "for finding in doc.missing():\n", " print(finding.message)" ] }, { "cell_type": "markdown", "id": "30", "metadata": {}, "source": [ "### Cycles\n", "\n", "The error-correction cycles are the last required section. A cycle lists its steps, each naming a syndrome measurement variant and a repeat count. A step refers to the variant object itself. The repeat count `ref(code).d` refers to the code distance instead of stating the number 3. With the cycles added, `missing()` is empty: the qubit layout, the decoder configuration and the properties that follow are optional." ] }, { "cell_type": "code", "execution_count": null, "id": "31", "metadata": {}, "outputs": [], "source": [ "doc.add_error_correction_cycle_variant(\n", " name=\"repeated_sequential\",\n", " steps=(ECCycleStep(measurement=sequential, repeat=ref(code).d),),\n", " fault_tolerant=False,\n", " description=\"d rounds of sequential syndrome measurement.\",\n", ")\n", "doc.add_error_correction_cycle_variant(\n", " name=\"repeated_parallel\",\n", " steps=(ECCycleStep(measurement=parallel, repeat=ref(code).d),),\n", " fault_tolerant=False,\n", " description=\"d rounds of parallel syndrome measurement.\",\n", " references=(landahl,),\n", ")\n", "\n", "print(doc.missing())" ] }, { "cell_type": "markdown", "id": "32", "metadata": {}, "source": [ "### Qubit layout\n", "\n", "The optional qubit layout consists of the cell complex of the 4.8.8 tiling, with seven vertices, the edges between them and three colored faces; an optional embedding of the vertices in the plane; and the placement of the registers: the data qubits on the vertices and the syndrome ancillas on the faces, ancilla i on face i, which carries check i." ] }, { "cell_type": "code", "execution_count": null, "id": "33", "metadata": {}, "outputs": [], "source": [ "doc.set_qubit_layout(QubitLayout(\n", " tiling_type=\"4.8.8\",\n", " topology=\"planar\",\n", " cell_complex=CellComplex(\n", " num_vertices=7,\n", " edges=[[0, 1], [0, 5], [1, 2], [1, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]],\n", " faces=(\n", " Face(vertices=[2, 4, 3, 1], color=0),\n", " Face(vertices=[0, 1, 3, 5], color=1),\n", " Face(vertices=[3, 4, 6, 5], color=2),\n", " ),\n", " ),\n", " embedding=Embedding(\n", " dimension=2,\n", " coordinate_type=\"cartesian\",\n", " vertex_coordinates=[\n", " [0.0, 1.0], [2.0, 1.0], [6.0, 1.0], [3.0, 2.0], [5.0, 2.0], [3.0, 4.0], [5.0, 4.0],\n", " ],\n", " ),\n", " qubit_placement={\n", " doc.data_qreg: CellPlacement(cell=CellType.VERTEX, mapping=[0, 1, 2, 3, 4, 5, 6]),\n", " syndrome: CellPlacement(cell=CellType.FACE, mapping=[0, 1, 2]),\n", " },\n", "))" ] }, { "cell_type": "markdown", "id": "34", "metadata": {}, "source": [ "### Decoders\n", "\n", "The decoder configuration lists the syndrome decoders the implementation supports. Tesseract needs no further information. Chromobius needs a color for every check, given as a `color` tag; here the tag refers to the face colors of the qubit layout, which is why the layout had to be added first." ] }, { "cell_type": "code", "execution_count": null, "id": "35", "metadata": {}, "outputs": [], "source": [ "doc.add_decoder(slug=\"tesseract\")\n", "\n", "face_colors = ref(QubitLayout).cell_complex.faces.each.color\n", "doc.add_decoder(slug=\"chromobius\", tags=(\n", " DecoderTag(name=\"color\", by_source={SyndromeSource.H_X: face_colors, SyndromeSource.H_Z: face_colors}),\n", "))\n", "print(face_colors)" ] }, { "cell_type": "markdown", "id": "36", "metadata": {}, "source": [ "Instead of a reference, a tag can give explicit values for the syndrome registers of a particular variant, with `DecoderTag(name=\"color\", overrides={variant: {register: values}})`." ] }, { "cell_type": "markdown", "id": "37", "metadata": {}, "source": [ "### Properties\n", "\n", "The properties hold the file's metadata, such as author, license and description. `creator` names the software that wrote the file. When it is not set, saving records the `qecx` package and its version, as returned by `qecx_creator()`; here it is set explicitly to the same value, so that the document in memory equals the saved file." ] }, { "cell_type": "code", "execution_count": null, "id": "38", "metadata": {}, "outputs": [], "source": [ "doc.set_properties(Properties(\n", " author=\"Haiqu\",\n", " creator=qecx_creator(),\n", " license=\"CC-BY-4.0\",\n", " description=\"Distance-3 triangular 4.8.8 color code [[7,1,3]], a self-dual CSS code.\",\n", "))" ] }, { "cell_type": "code", "execution_count": null, "id": "39", "metadata": {}, "outputs": [], "source": [ "doc.view().summary()" ] }, { "cell_type": "markdown", "id": "40", "metadata": {}, "source": [ "## Validating and saving\n", "\n", "`validate()` checks the document against every rule of the format and returns the findings; an empty tuple means the document is valid and complete." ] }, { "cell_type": "code", "execution_count": null, "id": "41", "metadata": {}, "outputs": [], "source": [ "doc.validate()" ] }, { "cell_type": "markdown", "id": "42", "metadata": {}, "source": [ "`save()` validates the document again and then writes it. The `layout` argument decides where the larger parts, such as circuits, matrices and the cell complex, are stored: inside the JSON text or as separate files in a ZIP archive.\n", "\n", "| `layout=` | Where each part is stored |\n", "| --- | --- |\n", "| `\"preserve\"` (default) | where it was when the document was loaded, or as set with `set_externalization`; a part with no recorded place follows the rest of the document, and in a new document is placed as under `\"auto\"` |\n", "| `\"inline\"` | inside the JSON text |\n", "| `\"auto\"` | in a separate file once it is larger than `auto_threshold_bytes` (1024 by default) |\n", "| `\"external\"` | in a separate file |\n", "\n", "The file is a ZIP archive as soon as at least one part is stored separately, and plain JSON text otherwise." ] }, { "cell_type": "code", "execution_count": null, "id": "43", "metadata": {}, "outputs": [], "source": [ "inline_path = WORKDIR / \"color_488_d3.qecx\"\n", "archive_path = WORKDIR / \"color_488_d3_archive.qecx\"\n", "doc.save(inline_path, layout=\"inline\")\n", "doc.save(archive_path, layout=\"external\")\n", "\n", "for path in (inline_path, archive_path):\n", " kind = \"ZIP archive\" if zipfile.is_zipfile(path) else \"JSON text\"\n", " print(f\"{path.name:28s} {path.stat().st_size:6d} bytes {kind}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "44", "metadata": {}, "outputs": [], "source": [ "with zipfile.ZipFile(archive_path) as archive:\n", " for member in archive.namelist():\n", " print(member)" ] }, { "cell_type": "markdown", "id": "45", "metadata": {}, "source": [ "Both files load back into a document equal to the original:" ] }, { "cell_type": "code", "execution_count": null, "id": "46", "metadata": {}, "outputs": [], "source": [ "print(\"from JSON text: \", QECXDocument.load(inline_path) == doc)\n", "print(\"from ZIP archive:\", QECXDocument.load(archive_path) == doc)" ] }, { "cell_type": "markdown", "id": "47", "metadata": {}, "source": [ "## Editing an existing file\n", "\n", "A loaded file is edited with the same methods. Here the file saved above gets a further logical gate, the transversal S gate: for this code, an S† gate on every data qubit implements the logical S gate." ] }, { "cell_type": "code", "execution_count": null, "id": "48", "metadata": {}, "outputs": [], "source": [ "edited = QECXDocument.load(inline_path)\n", "\n", "circuit = QuantumCircuit(q_data)\n", "circuit.sdg(q_data)\n", "\n", "s_gate = LogicalGateVariant(\n", " name=\"transversal\",\n", " gate=\"s\",\n", " operands=(Operand(block=0, logical_qubit=None),),\n", " circuit=circuit,\n", " registers={\n", " q_data: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=edited.data_qreg, block_index=0),\n", " },\n", " fault_tolerant=True,\n", " description=\"S† gate on every data qubit.\",\n", " references=(bombin,),\n", ")\n", "edited.add_operation(s_gate)\n", "\n", "print(sorted(edited.logical_gates))" ] }, { "cell_type": "markdown", "id": "49", "metadata": {}, "source": [ "The objects in a document are frozen. To change one, a modified copy is built, here with `dataclasses.replace`, and passed to `replace_operation`. The document then also updates everything that refers to the old object; here the cycle `repeated_sequential` is rebuilt around the new variant. Objects read from the document before the change are outdated afterwards and should be read again." ] }, { "cell_type": "code", "execution_count": null, "id": "50", "metadata": {}, "outputs": [], "source": [ "old = edited.syndrome_measurements[\"sequential\"]\n", "cycle_before = edited.error_correction_cycles[\"repeated_sequential\"]\n", "\n", "new = edited.replace_operation(\n", " old, replace(old, description=\"Sequential syndrome measurement: Z checks, then X checks, one check at a time.\"))\n", "\n", "cycle_after = edited.error_correction_cycles[\"repeated_sequential\"]\n", "print(\"cycle rebuilt: \", cycle_after is not cycle_before)\n", "print(\"step uses the new variant: \", cycle_after.steps[0].measurement is new)" ] }, { "cell_type": "markdown", "id": "51", "metadata": {}, "source": [ "An object that something still refers to cannot be removed; the error names what refers to it:" ] }, { "cell_type": "code", "execution_count": null, "id": "52", "metadata": {}, "outputs": [], "source": [ "try:\n", " edited.remove_operation(new)\n", "except QECXAuthoringError as error:\n", " print(error)" ] }, { "cell_type": "markdown", "id": "53", "metadata": {}, "source": [ "## Repairing a file\n", "\n", "A file that breaks a rule of the format fails to load with a `QECXValidationFailedError`, which lists the findings. Here a logical X operator contains a Z factor, which a CSS code does not allow (rule `CSS_LOGICAL_PURITY`)." ] }, { "cell_type": "code", "execution_count": null, "id": "54", "metadata": {}, "outputs": [], "source": [ "data = json.loads(inline_path.read_text(encoding=\"utf-8\"))\n", "data[\"code\"][\"logical_operators\"][\"X\"] = [\"XXZIIII\"]\n", "broken_path = WORKDIR / \"broken.qecx\"\n", "with broken_path.open(\"w\", encoding=\"utf-8\") as file:\n", " json.dump(data, file)\n", "\n", "try:\n", " QECXDocument.load(broken_path)\n", "except QECXValidationFailedError as error:\n", " print(type(error).__name__)\n", " for finding in error.findings:\n", " print(f\" {finding.rule_id} {finding.path}: {finding.message}\")" ] }, { "cell_type": "markdown", "id": "55", "metadata": {}, "source": [ "With `validate=False`, the file loads without the rule checks, provided each object in it can still be built. The document can then be inspected and repaired, here with `update_code_data`, and saved once it validates." ] }, { "cell_type": "code", "execution_count": null, "id": "56", "metadata": {}, "outputs": [], "source": [ "broken = QECXDocument.load(broken_path, validate=False)\n", "for finding in broken.validate():\n", " print(f\"{finding.severity} {finding.rule_id} {finding.path}\")\n", " print(f\" {finding.message}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "57", "metadata": {}, "outputs": [], "source": [ "broken.update_code_data(logical_operators_X=(PauliProductOperator.from_big_endian(\"XXXIIII\"),))\n", "print(broken.validate())\n", "broken.save(WORKDIR / \"repaired.qecx\")" ] }, { "cell_type": "markdown", "id": "58", "metadata": {}, "source": [ "## Codes with more than one logical qubit\n", "\n", "The [[4, 2, 2]] code encodes two logical qubits in four data qubits; its logical operators come in pairs, one for each logical qubit. The labelling of the two logical qubits follows Knill (2004)." ] }, { "cell_type": "code", "execution_count": null, "id": "59", "metadata": {}, "outputs": [], "source": [ "code_422 = CSSCodeData(\n", " n=4, k=2, d=2,\n", " H_X=np.array([[1, 1, 1, 1]], dtype=np.uint8),\n", " H_Z=np.array([[1, 1, 1, 1]], dtype=np.uint8),\n", " logical_operators_X=(PauliProductOperator.from_big_endian(\"XXII\"),\n", " PauliProductOperator.from_big_endian(\"XIXI\")),\n", " logical_operators_Z=(PauliProductOperator.from_big_endian(\"ZIZI\"),\n", " PauliProductOperator.from_big_endian(\"ZZII\")),\n", ")\n", "doc_422 = QECXDocument(code_422, code_name=\"[[4,2,2]] Code\")\n", "knill = doc_422.add_reference(\n", " key=\"knill_2004\",\n", " title=\"Fault-Tolerant Postselected Quantum Computation: Schemes\",\n", " authors=\"E. Knill\",\n", " year=2004,\n", " arxiv=\"quant-ph/0402171\",\n", ")" ] }, { "cell_type": "markdown", "id": "60", "metadata": {}, "source": [ "A gate on a single logical qubit names that qubit in its operand: `Operand(block=0, logical_qubit=0)` or `logical_qubit=1`. Each logical X gate here applies Pauli X gates on the support of that qubit's logical X operator. The document lists the two gates under separate operands:" ] }, { "cell_type": "code", "execution_count": null, "id": "61", "metadata": {}, "outputs": [], "source": [ "q_data_422 = QuantumRegister(4, \"q_data\")\n", "data_decl_422 = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc_422.data_qreg, block_index=0)\n", "\n", "# Support of logical X on logical qubit 0 (XXII) and 1 (XIXI).\n", "for logical_qubit, support in enumerate([[0, 1], [0, 2]]):\n", " circuit = QuantumCircuit(q_data_422)\n", " for qubit in support:\n", " circuit.x(q_data_422[qubit])\n", " doc_422.add_operation(LogicalGateVariant(\n", " name=\"transversal\",\n", " gate=\"x\",\n", " operands=(Operand(block=0, logical_qubit=logical_qubit),),\n", " circuit=circuit,\n", " registers={q_data_422: data_decl_422},\n", " fault_tolerant=True,\n", " ))\n", "\n", "for gate, groups in doc_422.logical_gates.items():\n", " for operands, group in groups.items():\n", " print(gate, operands, list(group))" ] }, { "cell_type": "markdown", "id": "62", "metadata": {}, "source": [ "The document is not yet complete; a file for this code would also need:" ] }, { "cell_type": "code", "execution_count": null, "id": "63", "metadata": {}, "outputs": [], "source": [ "for finding in doc_422.missing():\n", " print(finding.message)" ] }, { "cell_type": "code", "execution_count": null, "id": "64", "metadata": {}, "outputs": [], "source": [ "shutil.rmtree(WORKDIR, ignore_errors=True)" ] }, { "cell_type": "markdown", "id": "65", "metadata": {}, "source": [ "## Next steps\n", "\n", "- The tutorial [Using a QECX file](using_qecx_files.ipynb) shows how to read and view a file.\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.16" } }, "nbformat": 4, "nbformat_minor": 5 }