Authoring a QECX file

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, 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.

To run this tutorial as a notebook, install the package with its viewer extra in an environment with Jupyter:

pip install "python-qecx[viewer]"

The tutorial writes its files to a temporary directory, which the last cell removes.

import json
import shutil
import tempfile
import zipfile
from dataclasses import replace
from pathlib import Path

import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister

from qecx import (
    CellComplex,
    CellPlacement,
    CellType,
    CSSCodeData,
    DataMeasurementVariant,
    DecoderTag,
    DynamicRegisterDecl,
    ECCycleStep,
    Embedding,
    Face,
    InheritedRegisterDecl,
    LogicalGateVariant,
    MeasurementBasis,
    Operand,
    PauliProductOperator,
    Properties,
    QECXAuthoringError,
    QECXDocument,
    QECXValidationFailedError,
    QubitLayout,
    Reference,
    RegisterPurpose,
    RegisterScope,
    RegisterTemplateEntry,
    StatePreparationVariant,
    SyndromeCregDecl,
    SyndromeMeasurementVariant,
    SyndromeSource,
    TransversalReadoutCregDecl,
    qecx_creator,
    ref,
)

WORKDIR = Path(tempfile.mkdtemp(prefix="qecx_authoring_"))

Building a document

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.

Code

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.

H = np.array([
    [0, 1, 1, 1, 1, 0, 0],
    [1, 1, 0, 1, 0, 1, 0],
    [0, 0, 0, 1, 1, 1, 1],
], dtype=np.uint8)

code = CSSCodeData(
    n=7, k=1, d=3,
    H_X=H,
    H_Z=H,
    logical_operators_X=(PauliProductOperator.from_big_endian("XXXIIII"),),
    logical_operators_Z=(PauliProductOperator.from_big_endian("ZZZIIII"),),
)
doc = QECXDocument(code, code_name="Distance-3 Triangular 4.8.8 Color Code")

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:

for finding in doc.missing():
    print(finding.message)
operations.state_preparation is required but the document holds none.
operations.syndrome_measurement is required but the document holds none.
operations.logical_gates is required but the document holds none.
operations.data_measurement is required but the document holds none.
error_correction_cycle is required but the document holds none.

References

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.

bombin = doc.add_reference(
    key="bombin_martin_delgado_2006",
    title="Topological quantum distillation",
    authors="H. Bombín and M. A. Martín-Delgado",
    year=2006,
    doi="10.1103/PhysRevLett.97.180501",
    arxiv="quant-ph/0605138",
    note="Defines the color code family (primary reference)",
)

Registers

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:

print(doc.data_qreg)

syndrome = doc.add_ancilla_register_template(
    RegisterTemplateEntry("syndrome", 3, RegisterPurpose.SYNDROME))
print(syndrome)
RegisterTemplateEntry(name='data_qreg', size=7, purpose=<RegisterPurpose.LOGICAL_DATA: 'logical_data'>, purpose_description=None)
RegisterTemplateEntry(name='syndrome', size=3, purpose=<RegisterPurpose.SYNDROME: 'syndrome'>, purpose_description=None)

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.

q_data = QuantumRegister(code.n, "q_data")
a_syndrome = QuantumRegister(syndrome.size, "a_syndrome")

data_decl = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg)
syndrome_decl = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=syndrome)
syndrome_bits_decl = DynamicRegisterDecl(scope=RegisterScope.OUTPUT, size=3, purpose=RegisterPurpose.SYNDROME)

Gadgets

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.

State preparation

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.

encoder = QuantumCircuit(q_data)
for qubit in [0, 1, 3]:
    encoder.h(q_data[qubit])
for control, target in [(0, 2), (0, 4), (0, 5), (1, 2), (1, 5), (1, 6), (3, 4), (3, 5), (3, 6)]:
    encoder.cx(q_data[control], q_data[target])
encoder.draw("mpl")
../../_images/0982bed6d31df4aa8c26732ae951d8b86ea01a1d4ef8f1b7f7b8497d01e11bf5.png
doc.add_operation(StatePreparationVariant(
    name="css_encoder",
    state="0",
    circuit=encoder,
    registers={q_data: data_decl},
    fault_tolerant=False,
    description="Encoding circuit for the logical state |0⟩.",
))

for finding in doc.missing():
    print(finding.message)
operations.syndrome_measurement is required but the document holds none.
operations.logical_gates is required but the document holds none.
operations.data_measurement is required but the document holds none.
error_correction_cycle is required but the document holds none.

Syndrome measurement, sequential

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.

# Data qubits of each check in CNOT order; the same faces carry the Z and the X checks.
check_order = [[1, 2, 3, 4], [0, 1, 3, 5], [3, 4, 5, 6]]

c_z_syndrome = ClassicalRegister(3, "c_z_syndrome")
c_x_syndrome = ClassicalRegister(3, "c_x_syndrome")
circuit = QuantumCircuit(q_data, a_syndrome, c_z_syndrome, c_x_syndrome)
for check, qubits in enumerate(check_order):
    circuit.reset(a_syndrome[check])
    for qubit in qubits:
        circuit.cx(q_data[qubit], a_syndrome[check])
    circuit.measure(a_syndrome[check], c_z_syndrome[check])
circuit.barrier(q_data, a_syndrome)
for check, qubits in enumerate(check_order):
    circuit.reset(a_syndrome[check])
    circuit.h(a_syndrome[check])
    for qubit in qubits:
        circuit.cx(a_syndrome[check], q_data[qubit])
    circuit.h(a_syndrome[check])
    circuit.measure(a_syndrome[check], c_x_syndrome[check])

circuit.draw("mpl", fold=-1)
../../_images/97eb4004eca01a60ce0b39cd5a7f9bcfc92b6d427768cc73a7a3896ef3340de6.png
sequential = SyndromeMeasurementVariant(
    name="sequential",
    circuit=circuit,
    registers={
        q_data: data_decl,
        a_syndrome: syndrome_decl,
        c_z_syndrome: syndrome_bits_decl,
        c_x_syndrome: syndrome_bits_decl,
    },
    syndrome_cregs=(
        SyndromeCregDecl(name="c_z_syndrome", source=SyndromeSource.H_Z),
        SyndromeCregDecl(name="c_x_syndrome", source=SyndromeSource.H_X),
    ),
    fault_tolerant=False,
    description="Z checks, then X checks, one check at a time.",
)
doc.add_operation(sequential)

for finding in doc.missing():
    print(finding.message)
operations.logical_gates is required but the document holds none.
operations.data_measurement is required but the document holds none.
error_correction_cycle is required but the document holds none.

Syndrome measurement, parallel

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.

# One row per time step: check (ancilla) -> data qubit it couples to in that step.
schedule = [
    {0: 3, 2: 5},
    {0: 4, 2: 6},
    {0: 1, 2: 3},
    {0: 2, 1: 5, 2: 4},
    {},
    {1: 3},
    {1: 0},
    {1: 1},
]

circuit = QuantumCircuit(q_data, a_syndrome, c_x_syndrome, c_z_syndrome)
circuit.reset(a_syndrome)
circuit.h(a_syndrome)
circuit.barrier(q_data, a_syndrome)
for step in schedule:
    for check, qubit in step.items():
        circuit.cx(a_syndrome[check], q_data[qubit])
    circuit.barrier(q_data, a_syndrome)
circuit.h(a_syndrome)
circuit.measure(a_syndrome, c_x_syndrome)
circuit.reset(a_syndrome)
circuit.barrier(q_data, a_syndrome)
for step in schedule:
    for check, qubit in step.items():
        circuit.cx(q_data[qubit], a_syndrome[check])
    circuit.barrier(q_data, a_syndrome)
circuit.measure(a_syndrome, c_z_syndrome)

circuit.draw("mpl", fold=-1)
../../_images/4fe622aad43a44853b3bdafd0d97ab379f138abbcd3b38bfb395fab7db5c5dbf.png
landahl = Reference(
    key="landahl_anderson_rice_2011",
    title="Fault-tolerant quantum computing with color codes",
    authors="A. J. Landahl, J. T. Anderson, and P. R. Rice",
    year=2011,
    arxiv="1108.5738",
    note="Locality-respecting syndrome schedule used by syndrome_measurement.parallel",
)
parallel = SyndromeMeasurementVariant(
    name="parallel",
    circuit=circuit,
    registers={
        q_data: data_decl,
        a_syndrome: syndrome_decl,
        c_x_syndrome: syndrome_bits_decl,
        c_z_syndrome: syndrome_bits_decl,
    },
    syndrome_cregs=(
        SyndromeCregDecl(name="c_x_syndrome", source=SyndromeSource.H_X),
        SyndromeCregDecl(name="c_z_syndrome", source=SyndromeSource.H_Z),
    ),
    fault_tolerant=False,
    description="X checks, then Z checks, after the schedule of Landahl, Anderson and Rice.",
    references=(landahl,),
)
doc.add_operation(parallel)
print(list(doc.syndrome_measurements), "default:", doc.syndrome_measurements.default.name)
['sequential', 'parallel'] default: sequential

Logical gates

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.

circuit = QuantumCircuit(q_data)
circuit.h(q_data)

doc.add_operation(LogicalGateVariant(
    name="transversal",
    gate="h",
    operands=(Operand(block=0, logical_qubit=None),),
    circuit=circuit,
    registers={q_data: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=0)},
    fault_tolerant=True,
    description="Hadamard gate on every data qubit.",
    references=(bombin,),
))

for finding in doc.missing():
    print(finding.message)
operations.data_measurement is required but the document holds none.
error_correction_cycle is required but the document holds none.

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.

q_data_ctrl = QuantumRegister(code.n, "q_data_ctrl")
q_data_tgt = QuantumRegister(code.n, "q_data_tgt")
circuit = QuantumCircuit(q_data_ctrl, q_data_tgt)
circuit.cx(q_data_ctrl, q_data_tgt)

doc.add_operation(LogicalGateVariant(
    name="transversal",
    gate="cx",
    operands=(
        Operand(block=0, logical_qubit=None, role="control"),
        Operand(block=1, logical_qubit=None, role="target"),
    ),
    circuit=circuit,
    registers={
        q_data_ctrl: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=0),
        q_data_tgt: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc.data_qreg, block_index=1),
    },
    fault_tolerant=True,
    description="CNOT gates between corresponding data qubits of two code blocks.",
))
print(sorted(doc.logical_gates))
['cx', 'h']

Data measurement

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.

c_data_meas = ClassicalRegister(code.n, "c_data_meas")
circuit = QuantumCircuit(q_data, c_data_meas)
circuit.measure(q_data, c_data_meas)

doc.add_operation(DataMeasurementVariant(
    name="direct",
    basis=MeasurementBasis.Z,
    circuit=circuit,
    result_creg=c_data_meas,
    registers={
        q_data: data_decl,
        c_data_meas: DynamicRegisterDecl(
            scope=RegisterScope.OUTPUT, size=code.n, purpose=RegisterPurpose.LOGICAL_DATA),
    },
    transversal_readout_cregs=(TransversalReadoutCregDecl(name="c_data_meas", source=SyndromeSource.H_Z),),
    fault_tolerant=True,
    description="Z-basis measurement of every data qubit.",
))

for finding in doc.missing():
    print(finding.message)
error_correction_cycle is required but the document holds none.

Cycles

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.

doc.add_error_correction_cycle_variant(
    name="repeated_sequential",
    steps=(ECCycleStep(measurement=sequential, repeat=ref(code).d),),
    fault_tolerant=False,
    description="d rounds of sequential syndrome measurement.",
)
doc.add_error_correction_cycle_variant(
    name="repeated_parallel",
    steps=(ECCycleStep(measurement=parallel, repeat=ref(code).d),),
    fault_tolerant=False,
    description="d rounds of parallel syndrome measurement.",
    references=(landahl,),
)

print(doc.missing())
()

Qubit layout

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.

doc.set_qubit_layout(QubitLayout(
    tiling_type="4.8.8",
    topology="planar",
    cell_complex=CellComplex(
        num_vertices=7,
        edges=[[0, 1], [0, 5], [1, 2], [1, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6]],
        faces=(
            Face(vertices=[2, 4, 3, 1], color=0),
            Face(vertices=[0, 1, 3, 5], color=1),
            Face(vertices=[3, 4, 6, 5], color=2),
        ),
    ),
    embedding=Embedding(
        dimension=2,
        coordinate_type="cartesian",
        vertex_coordinates=[
            [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],
        ],
    ),
    qubit_placement={
        doc.data_qreg: CellPlacement(cell=CellType.VERTEX, mapping=[0, 1, 2, 3, 4, 5, 6]),
        syndrome: CellPlacement(cell=CellType.FACE, mapping=[0, 1, 2]),
    },
))

Decoders

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.

doc.add_decoder(slug="tesseract")

face_colors = ref(QubitLayout).cell_complex.faces.each.color
doc.add_decoder(slug="chromobius", tags=(
    DecoderTag(name="color", by_source={SyndromeSource.H_X: face_colors, SyndromeSource.H_Z: face_colors}),
))
print(face_colors)
SequenceRef(path='qubit_layout.cell_complex.faces.*.color')

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}}).

Properties

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.

doc.set_properties(Properties(
    author="Haiqu",
    creator=qecx_creator(),
    license="CC-BY-4.0",
    description="Distance-3 triangular 4.8.8 color code [[7,1,3]], a self-dual CSS code.",
))
doc.view().summary()
Distance-3 Triangular 4.8.8 Color Code  --  CSS  n=7  k=1  d=3  QECX v0.1
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Sections
├── Code
│   ├── H_X: 3x7 dense
│   ├── H_Z: 3x7 dense
│   ├── Logical X: XXXIIII
│   └── Logical Z: ZZZIIII
├── Registers
│   └── Per Code Block
│       ├── data_qreg[7] (logical_data)
│       └── syndrome[3] (syndrome)
├── Qubit Layout
│   ├── Tiling Type: 4.8.8
│   ├── Topology: planar
│   ├── Cell Complex: 7 vertices, 9 edges, 3 faces
│   ├── Embedding: dimension 2, coordinates cartesian
│   └── Qubit Placement: data_qreg (vertex, 7 qubits), syndrome (face, 3 qubits)
├── Operations
│   ├── State Preparation
│   │   └── |0_L⟩  1 variant  default: css_encoder  (css_encoder)
│   ├── Syndrome Measurement  2 variants  default: sequential  (sequential, parallel)
│   ├── Data Measurement
│   │   └── Z-basis  1 variant  default: direct  (direct)
│   └── Logical Gates  h, cx
├── Error Correction Cycle
│   ├── repeated_sequential (default) (non-FT)
│   │   ├── d rounds of sequential syndrome measurement.
│   │   └── Step 1: syndrome_measurement.sequential x code.d = 3
│   └── repeated_parallel (non-FT)
│       ├── d rounds of parallel syndrome measurement.
│       └── Step 1: syndrome_measurement.parallel x code.d = 3
├── Decoders
│   ├── Tesseract (tesseract)
│   └── Chromobius (chromobius)
└── Properties
    ├── Author: Haiqu
    ├── Creator: python-qecx 0.1.0
    ├── License: CC-BY-4.0
    ├── Description: Distance-3 triangular 4.8.8 color code [[7,1,3]], a self-dual CSS code.
    └── References
        ├── H. Bombín and M. A. Martín-Delgado, "Topological quantum distillation," 
        │   doi:10.1103/PhysRevLett.97.180501 arXiv:quant-ph/0605138 (2006). Defines the color code family (primary
        │   reference)
        └── A. J. Landahl, J. T. Anderson, and P. R. Rice, "Fault-tolerant quantum computing with color codes," 
            arXiv:1108.5738 (2011). Locality-respecting syndrome schedule used by syndrome_measurement.parallel

Validating and saving

validate() checks the document against every rule of the format and returns the findings; an empty tuple means the document is valid and complete.

doc.validate()
()

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.

layout=

Where each part is stored

"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"

"inline"

inside the JSON text

"auto"

in a separate file once it is larger than auto_threshold_bytes (1024 by default)

"external"

in a separate file

The file is a ZIP archive as soon as at least one part is stored separately, and plain JSON text otherwise.

inline_path = WORKDIR / "color_488_d3.qecx"
archive_path = WORKDIR / "color_488_d3_archive.qecx"
doc.save(inline_path, layout="inline")
doc.save(archive_path, layout="external")

for path in (inline_path, archive_path):
    kind = "ZIP archive" if zipfile.is_zipfile(path) else "JSON text"
    print(f"{path.name:28s} {path.stat().st_size:6d} bytes  {kind}")
color_488_d3.qecx             15054 bytes  JSON text
color_488_d3_archive.qecx      6257 bytes  ZIP archive
with zipfile.ZipFile(archive_path) as archive:
    for member in archive.namelist():
        print(member)
manifest.json
code/H_X.json
code/H_Z.json
code/logical_operators_X.txt
code/logical_operators_Z.txt
circuits/state_preparation_0_css_encoder.qasm
circuits/data_measurement_Z_direct.qasm
circuits/logical_gates_h_0_transversal.qasm
circuits/logical_gates_cx_0_transversal.qasm
circuits/syndrome_measurement_sequential.qasm
circuits/syndrome_measurement_parallel.qasm
cycles/repeated_sequential.json
cycles/repeated_parallel.json
decoders/tesseract.json
decoders/chromobius.json
layout/edges.json
layout/faces.json
layout/vertex_coordinates.json
layout/qubit_placement.json
references.json

Both files load back into a document equal to the original:

print("from JSON text:  ", QECXDocument.load(inline_path) == doc)
print("from ZIP archive:", QECXDocument.load(archive_path) == doc)
from JSON text:   True
from ZIP archive: True

Editing an existing file

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.

edited = QECXDocument.load(inline_path)

circuit = QuantumCircuit(q_data)
circuit.sdg(q_data)

s_gate = LogicalGateVariant(
    name="transversal",
    gate="s",
    operands=(Operand(block=0, logical_qubit=None),),
    circuit=circuit,
    registers={
        q_data: InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=edited.data_qreg, block_index=0),
    },
    fault_tolerant=True,
    description="S† gate on every data qubit.",
    references=(bombin,),
)
edited.add_operation(s_gate)

print(sorted(edited.logical_gates))
['cx', 'h', 's']

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.

old = edited.syndrome_measurements["sequential"]
cycle_before = edited.error_correction_cycles["repeated_sequential"]

new = edited.replace_operation(
    old, replace(old, description="Sequential syndrome measurement: Z checks, then X checks, one check at a time."))

cycle_after = edited.error_correction_cycles["repeated_sequential"]
print("cycle rebuilt:              ", cycle_after is not cycle_before)
print("step uses the new variant:  ", cycle_after.steps[0].measurement is new)
cycle rebuilt:               True
step uses the new variant:   True

An object that something still refers to cannot be removed; the error names what refers to it:

try:
    edited.remove_operation(new)
except QECXAuthoringError as error:
    print(error)
variant 'sequential' is still referenced by ECCycleVariant 'repeated_sequential'

Repairing a file

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).

data = json.loads(inline_path.read_text(encoding="utf-8"))
data["code"]["logical_operators"]["X"] = ["XXZIIII"]
broken_path = WORKDIR / "broken.qecx"
with broken_path.open("w", encoding="utf-8") as file:
    json.dump(data, file)

try:
    QECXDocument.load(broken_path)
except QECXValidationFailedError as error:
    print(type(error).__name__)
    for finding in error.findings:
        print(f"    {finding.rule_id} {finding.path}: {finding.message}")
QECXValidationFailedError
    CSS_LOGICAL_PURITY code.logical_operators.X[0]: CSS X logical operator must be a pure-X Pauli string (only 'I' and 'X').

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.

broken = QECXDocument.load(broken_path, validate=False)
for finding in broken.validate():
    print(f"{finding.severity} {finding.rule_id} {finding.path}")
    print(f"    {finding.message}")
error CSS_LOGICAL_PURITY code.logical_operators.X[0]
    CSS X logical operator must be a pure-X Pauli string (only 'I' and 'X').
broken.update_code_data(logical_operators_X=(PauliProductOperator.from_big_endian("XXXIIII"),))
print(broken.validate())
broken.save(WORKDIR / "repaired.qecx")
()

Codes with more than one logical qubit

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).

code_422 = CSSCodeData(
    n=4, k=2, d=2,
    H_X=np.array([[1, 1, 1, 1]], dtype=np.uint8),
    H_Z=np.array([[1, 1, 1, 1]], dtype=np.uint8),
    logical_operators_X=(PauliProductOperator.from_big_endian("XXII"),
                         PauliProductOperator.from_big_endian("XIXI")),
    logical_operators_Z=(PauliProductOperator.from_big_endian("ZIZI"),
                         PauliProductOperator.from_big_endian("ZZII")),
)
doc_422 = QECXDocument(code_422, code_name="[[4,2,2]] Code")
knill = doc_422.add_reference(
    key="knill_2004",
    title="Fault-Tolerant Postselected Quantum Computation: Schemes",
    authors="E. Knill",
    year=2004,
    arxiv="quant-ph/0402171",
)

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:

q_data_422 = QuantumRegister(4, "q_data")
data_decl_422 = InheritedRegisterDecl(scope=RegisterScope.BLOCK, target=doc_422.data_qreg, block_index=0)

# Support of logical X on logical qubit 0 (XXII) and 1 (XIXI).
for logical_qubit, support in enumerate([[0, 1], [0, 2]]):
    circuit = QuantumCircuit(q_data_422)
    for qubit in support:
        circuit.x(q_data_422[qubit])
    doc_422.add_operation(LogicalGateVariant(
        name="transversal",
        gate="x",
        operands=(Operand(block=0, logical_qubit=logical_qubit),),
        circuit=circuit,
        registers={q_data_422: data_decl_422},
        fault_tolerant=True,
    ))

for gate, groups in doc_422.logical_gates.items():
    for operands, group in groups.items():
        print(gate, operands, list(group))
x (Operand(block=0, logical_qubit=0, role=None),) ['transversal']
x (Operand(block=0, logical_qubit=1, role=None),) ['transversal']

The document is not yet complete; a file for this code would also need:

for finding in doc_422.missing():
    print(finding.message)
operations.state_preparation is required but the document holds none.
operations.syndrome_measurement is required but the document holds none.
operations.data_measurement is required but the document holds none.
error_correction_cycle is required but the document holds none.
shutil.rmtree(WORKDIR, ignore_errors=True)

Next steps