qldpc.codes.quantum

Quantum error-correcting codes.

Attributes

FieldOrRingArray

Classes

BBCode

Bivariate bicycle code, or a quasi-cyclic code with polynomials in two variables.

BaconShorCode

Bacon-Shor code on a square grid, implemented as a subsystem hypergraph product code.

C4Code

A [[4, 2, 2]] code, commonly known as the "C4" code.

C6Code

A [[6, 2, 2]] code, commonly known as the "C6" code.

CHGPCode

Cyclic hypergraph product code.

CRCode

Repeated cyclic hypergraph product code.

FiveQubitCode

Smallest quantum error-correcting code.

FiveQuditCode

Smallest quantum error-correcting code.

GALACode

Group-Action Lift with Active orthogonality (GALA) code.

GeneralizedSurfaceCode

Surface or toric code defined on a multi-dimensional hypercubic lattice.

HGPCode

Hypergraph product code.

IcebergCode

A quantum error detecting code: [[n, n - 2, 2]].

LPCode

Lifted product code.

ManyHypercubeCode

The [[6**level, 4**level, 2**level]] concatenated many-hypercubes code.

QCCode

Quasi-cyclic code.

QTCode

Quantum Tanner code: a CSS code for qudits defined on the faces of a Cayley complex.

QuantumGolayCode

Quantum [[23, 1, 7]] Golay code, built from the classical [23, 12, 7] Golay code.

QuantumHammingCode

Quantum Hamming code, whose parity check matrices are classical Hamming codes.

QuantumReedMullerCode

Self-orthogonal CSS code from a classical Reed-Muller code.

SHPCode

Subsystem hypergraph product code.

SHYPSCode

Subsystem hypergraph product simplex (SHYPS) code.

SLPCode

Subsystem lifted product code.

SteaneCode

Smallest quantum error-correcting CSS code.

SurfaceCode

The one and only!

T4Code

Four-dimensional (2, 2) toric code.

TBCode

Two-block code.

TetrahedralCode

Smallest quantum error-correcting CSS code with a transversal non-Clifford (T) gate.

ToricCode

Surface code with periodic boundary conditions, encoding two logical qudits.

TrivialCode

The trivial code with single-qubit logical operators.

Module Contents

class qldpc.codes.quantum.BBCode(orders: collections.abc.Sequence[int] | dict[sympy.Symbol, int], poly_a: sympy.Basic, poly_b: sympy.Basic, field: int | type[galois.FieldArray] | None = None)[source]

Bases: QCCode

Bivariate bicycle code, or a quasi-cyclic code with polynomials in two variables.

A bivariate bicycle code is a CSS code with subcode parity check matrices

  • matrix_x = [A, B], and

  • matrix_z = [B.T, -A.T].

Here A and B are polynomials of the form A = sum_{i,j} A_{ij} x^i y^j, where

  • A_{ij} is a scalar coefficient (over some finite field),

  • x and y are, respectively, generators of cyclic groups of orders R_x and R_y, and

  • the monomial x^i y^j represents a tensor product of cyclic shift matrices.

A bivariate bicycle code is defined by… [1] two cyclic group orders, and [2] two bivariate polynomials. The polynomials should be sympy expressions such as 1 + x + x * y**2 with sympy.abc variables x and y. Group orders are, by default, associated with the free variables of the polynomials in lexicographic order. Group orders can also be assigned to variables explicitly with a dictionary, as in {x: 12, y: 6}.

The polynomials A and B induce a “canonical” layout of the data and check qubits of a BBCode. In the canonical layout, qubits are organized into plaquettes of four qubits that look like:

L X
Z R

where L and R are data qubits, and X and Z are check qubits. More specifically:

  • L and R data qubits are addressed by the left and right halves of matrix_x (or matrix_z).

  • X are check qubits measure X-type parity checks, and are associated with rows of matrix_x.

  • Z are check qubits measure Z-type parity checks, and are associated with rows of matrix_z.

These four-qubit plaquettes are arranged into a rectangular grid that is R_x plaquettes wide and R_y plaquettes tall, where R_x and R_y are the orders of the cyclic groups generated by x and y. Each qubit can then be labeled by coordinates (a, b) of a plaquette, corresponding to a row and column in the grid of plaquettes, and a “sector” (L, R, X, or Z) within a plaquette.

If we associate (L, R) ~ (0, 1), then the data qubit addressed by column qq of matrix_x (or matrix_z) has the label (sector, a, b) = numpy.unravel_index(qq, [2, R_x, R_y]). The integer index of a data qubit and its label are thereby related to each other by array reshaping. The label of a check qubit, whose numerical index is the index of a corresponding row in the full parity check matrix of a BBCode, is similarly obtained by associating (X, Z) ~ (0, 1).

The connections between data and check qubits can be read directly from the polynomials A and B:

  • If A_{ij} != 0, then…

    • every X qubit addresses an L qubit that is (i, j) plaquettes (right, up), and

    • every Z qubit addresses an R qubit that is (i, j) plaquettes (left, down).

  • If B_{ij} != 0, then…

    • every X qubit addresses an R qubit that is (i, j) plaquettes (right, up), and

    • every Z qubit addresses an L qubit that is (i, j) plaquettes (left, down).

Here the grid of plaquettes is assumed to have periodic boundary conditions, so going one plaquette “up” from the top row of the grid gets you to the bottom row of the grid.

References:

as_exponent_vector(monomial: sympy.Mul) → tuple[int, int][source]

Express the given monomial as a vector of exponents, as in x**3/y**2 -> (3, -2).

change_poly_basis(new_x: sympy.Mul, new_y: sympy.Mul, *polys: sympy.Basic) → list[sympy.Basic][source]

Change polynomial bases from (old_x, old_y) = self.symbols to (new_x, new_y).

get_equivalent_toric_layout_code_data() → collections.abc.Sequence[tuple[tuple[int, int], sympy.Poly, sympy.Poly]][source]

Get the generating data for equivalent BBCodes with “manifestly toric” layouts.

For simplicity, we consider BBCodes for qubits (with base field F_2) in the text below.

A BBCode has a manifestly toric layout if it is generated by polynomials that look like

poly_a = 1 + x + ..., and poly_b = 1 + y + ...,

We say that two BBCodes are “equivalent” if they can be obtained from one another by a permutation of data and check qubits. For qudit codes, we also allow “equivalent” BBCodes to differ by an overall sign of their Z-type parity checks, which does not change the code that these checks define.

To find an equivalent BBCode with a manifestly toric layout, we take

poly_a = sum_j A_j --> poly_a / A_k = 1 + sum_{j != k} A_j/A_k, and poly_b = sum_j B_j --> poly_b / B_l = 1 + sum_{j != l} B_j/B_l.

Each pair of terms (A_j/A_k, B_j/B_l) is then a candidate for cyclic group generators (g, h) for an equivalent BBCode.

This modification of polynomials and change-of-basis from the original generators (x, y) to (g, h) produces an equivalent BBCode so long as g and h satisfy the conditions in Lemma 4 of arXiv:2308.07915, which boils down to the requirement that

order(g) * order(h) = order(<g, h>) = order(<x, y>),

where (for example) <x, y> is the abelian group generated by x and y.

get_node_label(node: qldpc.objects.Node) → tuple[str, int, int][source]

Convert a node of this code’s Tanner graph into a qubit label.

The qubit label identifies the sector (L, R, X, Y) within a plaquette, and the coordinates of the plaquette that contains the given node (qubit).

static get_node_label_from_orders(node: qldpc.objects.Node, orders: tuple[int, int]) → tuple[str, int, int][source]

Get the label of a qubit in a BBCode with cyclic groups of the given orders.

The qubit label identifies the sector (L, R, X, Y) within a plaquette, and the coordinates of the plaquette that contains the given node (qubit).

get_order(vec: tuple[int, int]) → int[source]

What multiple of the vector hits the “origin” on the torus of plaquettes for this code?

The plaquettes for this code tile a torus with shape self.orders.

get_qubit_pos(qubit: qldpc.objects.Node | tuple[str, int, int], folded_layout: bool = False) → tuple[int, int][source]

Get the canonical position of a qubit in this code.

If folded_layout is True, “fold” the array of qubits as in Figure 2 of arXiv:2404.18809.

static get_qubit_pos_from_orders(qubit: qldpc.objects.Node | tuple[str, int, int], folded_layout: bool, orders: tuple[int, int]) → tuple[int, int][source]

Get the canonical position of a qubit in a BBCode with cyclic groups of the given orders.

If folded_layout is True, “fold” the array of qubits as in Figure 2 of arXiv:2404.18809.

is_valid_basis(vec_a: tuple[int, int], vec_b: tuple[int, int]) → bool[source]

Are the given vectors a valid basis for the plaquettes of this code?

The plaquettes for this code tile a torus with shape self.orders.

modular_inverse(basis: tuple[tuple[int, int], tuple[int, int]], aa: int, bb: int) → tuple[int, int][source]

Brute-force solve for the basis coefficients xx, yy of a target vector.

Solves xx * basis[0] + yy * basis[1] == (aa, bb) % self.orders for xx, yy.

orders: tuple[int, int]
symbols: tuple[sympy.Symbol, sympy.Symbol]
class qldpc.codes.quantum.BaconShorCode(rows: int, cols: int | None = None, field: int | type[galois.FieldArray] | None = None, *, set_logicals: bool = True)[source]

Bases: SHPCode

Bacon-Shor code on a square grid, implemented as a subsystem hypergraph product code.

References:

class qldpc.codes.quantum.C4Code[source]

Bases: IcebergCode

A [[4, 2, 2]] code, commonly known as the “C4” code.

References:

class qldpc.codes.quantum.C6Code[source]

Bases: qldpc.codes.common.CSSCode

A [[6, 2, 2]] code, commonly known as the “C6” code.

References:

class qldpc.codes.quantum.CHGPCode(dims: tuple[int, int] | int, poly_a: sympy.Basic, poly_b: sympy.Basic | None = None, field: int | type[galois.FieldArray] | None = None)[source]

Bases: HGPCode

Cyclic hypergraph product code.

A CHGPCode is a hypergraph product of classical CyclicCodes.

References:

class qldpc.codes.quantum.CRCode(bits: int, poly: sympy.Basic, field: int | type[galois.FieldArray] | None = None)[source]

Bases: HGPCode

Repeated cyclic hypergraph product code.

A CRCode is a hypergraph product of a CyclicCode and a RingCode.

References:

class qldpc.codes.quantum.FiveQubitCode[source]

Bases: FiveQuditCode

Smallest quantum error-correcting code.

References:

class qldpc.codes.quantum.FiveQuditCode(field: int | type[galois.FieldArray] | None = None)[source]

Bases: qldpc.codes.common.QuditCode

Smallest quantum error-correcting code.

Generalizes the better-known FiveQubitCode.

References:

class qldpc.codes.quantum.GALACode(generators_f: collections.abc.Sequence[qldpc.abstract.RingMember], generators_g: collections.abc.Sequence[qldpc.abstract.RingMember], num_active_rows: int, *, skip_validation: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Group-Action Lift with Active orthogonality (GALA) code.

A GALA code is a two-block CSS code built from two sequences of elements in a binary group algebra. Given generator sequences (F_0, …, F_{L/2-1}) and (G_0, …, G_{L/2-1}), construct block-circulant matrices F and G with entries:

F[i, j] = F_{j-i},
G[i, j] = G_{j-i},

where generator indices are taken modulo L/2. These matrices define parent check matrices:

parent_matrix_x = [F, G],
parent_matrix_z = [G.T, F.T].

The first J block rows of each parent matrix are the active rows that define the parity checks of the code. The remaining rows are latent rows and do not define stabilizers.

Each generator is a RingMember and may therefore be either a monomial, representing one group element, or a polynomial sum of group elements. GALA codes are currently supported only over GF(2).

The compact self-dual [[132, 30, 12]] code from arXiv:2608.07431 can be constructed by:

from qldpc import abstract, codes

ring = abstract.GroupRing(abstract.CyclicGroup(11))
x = ring.generators[0]
code = codes.GALACode(
    generators_f=[x**2, x**4, x**3, x**6, x**3, x**9],
    generators_g=[x**9, x**2, x**8, x**5, x**8, x**7],
    num_active_rows=5,
)
assert code.num_qubits == 132  # the block length n
assert code.dimension == 30  # the number of logical qubits k

# the maximum stabilizer weight, which for this code coincides numerically with the
# distance d = 12 reported in arXiv:2608.07431; computing the distance itself is
# intractable at this block length, so it is taken from the reference rather than checked
assert code.get_weight() == 12

References:

generators_f: tuple[qldpc.abstract.RingMember, ...]
generators_g: tuple[qldpc.abstract.RingMember, ...]
group: qldpc.abstract.Group
matrix_f: qldpc.abstract.RingArray
matrix_g: qldpc.abstract.RingArray
num_active_rows: int
num_blocks: int
parent_matrix_x: qldpc.abstract.RingArray
parent_matrix_z: qldpc.abstract.RingArray
ring: qldpc.abstract.GroupRing
class qldpc.codes.quantum.GeneralizedSurfaceCode(size: int, dim: int, field: int | type[galois.FieldArray] | None = None, *, periodic: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Surface or toric code defined on a multi-dimensional hypercubic lattice.

References:

class qldpc.codes.quantum.HGPCode(code_a: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], code_b: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | None = None, field: int | type[galois.FieldArray] | None = None, *, set_logicals: bool = True)[source]

Bases: qldpc.codes.common.CSSCode

Hypergraph product code.

A hypergraph product code AB is constructed from the parity check matrices of two classical codes, A and B.

Consider the following:

  • Code A has 3 data and 2 check bits.

  • Code B has 4 data and 3 check bits.

We represent data bits/qudits by circles (○) and check bits/qudits by squares (□).

Denote the Tanner graph of code C by G_C. The nodes of G_AB can be arranged into a matrix. The rows of this matrix are labeled by nodes of G_A, and columns by nodes of G_B. The matrix of nodes in G_AB can thus be organized into four sectors:

――――――――――――――――――――――――――――――――――
  | ○ ○ ○ ○ | □ □ □ ← nodes of G_B
――+―――――――――+――――――
○ | ○ ○ ○ ○ | □ □ □
○ | ○ ○ ○ ○ | □ □ □
○ | ○ ○ ○ ○ | □ □ □
――+―――――――――+――――――
□ | □ □ □ □ | ○ ○ ○
□ | □ □ □ □ | ○ ○ ○
↑ nodes of G_A
――――――――――――――――――――――――――――――――――

We identify each sector by two bits. In the example above:

  • sector (0, 0) has 3×4=12 data qudits

  • sector (0, 1) has 3×3=9 check qudits

  • sector (1, 0) has 2×4=8 check qudits

  • sector (1, 1) has 2×3=6 data qudits

Edges in G_AB are inherited across rows/columns from G_A and G_B. For example, if rows r_1 and r_2 share an edge in G_A, then the same is true in every column of G_AB.

By default, the check qudits in sectors…

  • (1, 0) of G_AB measure X-type operators, and

  • (0, 1) of G_AB measure Z-type operators.

This class contains two equivalent constructions of an HGPCode:

  • A construction based on Tanner graphs (as discussed above).

  • A construction based on check matrices, as originally introduced in arXiv:0903.0566.

The latter construction is less intuitive, but more efficient.

References:

Syndrome extraction, canonical logical operators, and exact distances additionally follow:

static get_canonical_logical_line_ops(matrix_a: galois.FieldArray, matrix_b: galois.FieldArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Canonical logical line operators for a hypergraph product code.

These operators are essentially those in Lemma 1 of arXiv:2204.10812v3, modified using pivot matrices similarly to Theorem VIII.10 of arXiv:2502.07150v1 to ensure pair-wise anti-commutation relations.

X-type logical operators are “horizontal” in sector (0, 0) and “vertical” in sector (1, 1). Vice versa for Z-type logical operators.

static get_graph_product(graph_a: qldpc._util.networkx.DiGraph, graph_b: qldpc._util.networkx.DiGraph) → qldpc._util.networkx.DiGraph[source]

Hypergraph product of two Tanner graphs.

static get_matrix_product(matrix_a: FieldOrRingArray, matrix_b: FieldOrRingArray) → tuple[FieldOrRingArray, FieldOrRingArray][source]

Hypergraph product of two parity check matrices.

static get_product_node_map(nodes_a: collections.abc.Collection[qldpc.objects.Node], nodes_b: collections.abc.Collection[qldpc.objects.Node]) → dict[tuple[qldpc.objects.Node, qldpc.objects.Node], qldpc.objects.Node][source]

Map (dictionary) that re-labels nodes in the hypergraph product of two codes.

static get_sector(node_a: qldpc.objects.Node, node_b: qldpc.objects.Node) → tuple[int, int][source]

Get the sector of a node in a graph product.

get_syndrome_subgraphs(*, strategy: str = 'smallest_last') → tuple[qldpc._util.networkx.DiGraph, ...][source]

Sequence of subgraphs of the Tanner graph that induces a syndrome extraction sequence.

See help(qldpc.codes.QuditCode.get_syndrome_subgraphs) for additional information.

The sequence here is essentially the sequence used for hypergraph product codes in Algorithm 2 of arXiv:2109.14609, modified to obviate the need to find a balanced ordering of Tanner graph vertices, and to group horizontal edges more coarsely than vertical ones.

More specifically, this method constructs Tanner subgraphs as follows:

  1. For the classical seed code that defines vertical edges of this HGPCode (self.code_a),

    color the edges of its Tanner graph, and number these colors starting from zero.

  2. Even edges get assigned a “north” or “south” direction if they are associated,

    respectively, with X-type or Z-type parity checks. Odd edges get assigned the opposite direction.

  3. Step 1 is repeated for the classical seed code that defines horizontal edges of this

    HGPCode (self.code_b), but the resulting edges get an “east” or “west” direction according to the parity of their color alone: even colors go east and odd colors go west, irrespective of parity check type.

Any two overlapping X-type and Z-type parity checks of an HGPCode share exactly two data qubits, so the induced circuit measures the correct syndrome only if the X-type gate comes before the Z-type gate on both of those qubits, or after it on both. The check-type term in step 2 is what enforces that, sending vertical edges of one color but opposite check type to opposite ends of the returned sequence; grouping vertical edges by color alone breaks it. Horizontal edges need no such term, and grouping them by color alone halves the number of subgraphs they require. Each color class of an edge coloring is a matching, so every subgraph, horizontal or vertical, addresses each qubit at most once and is therefore realizable as a single layer of gates.

Parameters:

strategy – The strategy used by nx.greedy_color to color edges of the Tanner graph. Default: “smallest_last”.

bias_tailoring_qubits
code_a: qldpc.codes.common.ClassicalCode
code_b: qldpc.codes.common.ClassicalCode
sector_size: numpy.typing.NDArray[numpy.int_]
class qldpc.codes.quantum.IcebergCode(size: int)[source]

Bases: qldpc.codes.common.CSSCode

A quantum error detecting code: [[n, n - 2, 2]].

References:

class qldpc.codes.quantum.LPCode(matrix_a: numpy.typing.NDArray[numpy.object_] | collections.abc.Sequence[collections.abc.Sequence[object]], matrix_b: numpy.typing.NDArray[numpy.object_] | collections.abc.Sequence[collections.abc.Sequence[object]] | None = None, *, set_logicals: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Lifted product code.

A lifted product code is essentially the same as a hypergraph product code, except that the parity check matrices are RingArrays, or matrices whose entries are members of a group algebra over a finite field F_q. Each of these entries can be “lifted” to a representation as orthogonal matrices over F_q, in which case the RingArray is interpreted as a block matrix; this is called “lifting” the RingArray.

As an example, the lift-connected surface code in Eq. (2) of https://arxiv.org/pdf/2401.02911v2 can be constructed by:

import numpy as np
from qldpc.abstract import CyclicGroup, GroupRing, RingArray
from qldpc.codes import RepetitionCode, LPCode

num_copies = 5  # the number of surface codes to stitch together
group = CyclicGroup(num_copies)
x = group.generators[0]  # generator of the cyclic group

# stitch together small surface codes by hand
ring = GroupRing(group)
rep_matrix = RingArray.build([[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1]], ring)
int_matrix = RingArray.build([[0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], ring)
code = LPCode(rep_matrix + int_matrix)

# stitch together larger surface codes
dist = 10  # distance of the individual surface codes
rep_matrix = RingArray.build(RepetitionCode(dist).matrix, ring)
int_matrix = RingArray.build(np.zeros((dist - 1, dist), dtype=int), ring)
for row in range(len(int_matrix)):
    int_matrix[row, row + 1] = x
code = LPCode(rep_matrix + int_matrix)

Notes:

  • A lifted product code with RingArrays of size 1×1 is a two-block code (more

    specifically, a two-block group-algebra code). If the base group of the RingArrays is a cyclic group, the resulting lifted product code is a generalized bicycle code.

  • A lifted product code with RingArrays whose entries get lifted to 1×1 matrices is a

    hypergraph product code built from the lifted RingArrays.

  • One way to get an LPCode: take a classical code with parity check matrix H and multiply it by

    a diagonal matrix D = diag(a_1, a_2, ... a_n), where all {a_j} are elements of a group algebra. The RingArray P = H @ D can then be used for one of the RingArrays of an LPCode.

References:

static get_canonical_logical_line_ops(matrix_a: qldpc.abstract.RingArray, matrix_b: qldpc.abstract.RingArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Canonical logical line operators for a subsystem lifted product code.

static get_canonical_ring_logical_line_ops(matrix_a: qldpc.abstract.RingArray, matrix_b: qldpc.abstract.RingArray) → tuple[qldpc.abstract.RingArray, qldpc.abstract.RingArray][source]

Canonical ring-logical line operators for a lifted product code.

Generalizes HGPCode.get_canonical_logical_line_ops.

static to_lifted_logical_ops(logical_ops_x: qldpc.abstract.RingArray, logical_ops_z: qldpc.abstract.RingArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Lift logical operators over a ring to logical operators over the base field.

bias_tailoring_qubits
matrix_a: qldpc.abstract.RingArray
matrix_b: qldpc.abstract.RingArray
sector_size: numpy.typing.NDArray[numpy.int_]
class qldpc.codes.quantum.ManyHypercubeCode(level: int = 1)[source]

Bases: qldpc.codes.common.CSSCode

The [[6**level, 4**level, 2**level]] concatenated many-hypercubes code.

References:

class qldpc.codes.quantum.QCCode(orders: collections.abc.Sequence[int] | dict[sympy.Symbol, int], poly_a: sympy.Basic, poly_b: sympy.Basic, field: int | type[galois.FieldArray] | None = None)[source]

Bases: TBCode

Quasi-cyclic code.

A QCCode is a two block code (TBCode) built out of matrices A and B that are chosen from a ring over an abelian group to ensure that A and B commute. More specifically, a QCCode is a CSS code with subcode parity check matrices

  • matrix_x = [A, B], and

  • matrix_z = [B.T, -A.T].

Here A and B are polynomials of the form A = sum_{i,j,k,...} A_{ijk...} x^i y^j z^k ..., where

  • A_{ijk…} is a scalar coefficient (over some finite field),

  • x, y, z, … are generators of cyclic groups of orders R_x, R_y, R_z, …

  • the monomial x^i y^j z^k ... represents a tensor product of cyclic shift matrices.

A quasi-cyclic code is defined by… [1] a sequence of cyclic group orders, and [2] two multivariate polynomials. The polynomials should be sympy expressions such as 1 + x + x * y**2 with sympy.abc variables x and y. Group orders are, by default, associated with the free variables of the polynomials in lexicographic order. Group orders can also be assigned to variables explicitly with a dictionary, as in {x: 12, y: 6}.

References:

Univariate quasi-cyclic codes are generalized bicycle codes:

Bivariate quasi-cyclic codes are bivariate bicycle codes; see the BBCode class.

get_canonical_form(poly: sympy.Basic, orders: tuple[int, ...] | None = None) → sympy.Expr[source]

Canonicalize the given polynomial, shifting exponents to (-order/2, order/2].

The polynomial is simplified first, so that its monomials denote distinct group elements and carry the coefficients that the base field gives them. Shifting the exponents of distinct simplified monomials leaves them distinct, so the terms below combine by addition alone.

get_simplified_form(poly: sympy.Basic, orders: tuple[int, ...] | None = None) → sympy.Poly[source]

Simplify the given polynomial with the relations satisfied by the cyclic generators.

A generator of a cyclic group of order R satisfies x**R = 1, so the exponent of a symbol matters only modulo its order, and two monomials whose exponents agree modulo the orders denote the same group element. Reducing every exponent into [0, order) therefore collects such monomials into a single term, whose coefficient is the sum of theirs in the base field, and a coefficient that sums to zero leaves no term at all. The polynomial is returned over all of the symbols of this code, including any that it does not address.

get_syndrome_subgraphs(*, strategy: str = '') → tuple[qldpc._util.networkx.DiGraph, ...][source]

Sequence of subgraphs of the Tanner graph that induces a syndrome extraction sequence.

See help(qldpc.codes.QuditCode.get_syndrome_subgraphs) for additional information.

The syndrome measurement circuit induced by the sequence of subgraphs constructed here generalizes the syndrome measurement circuit for BBCodes in arXiv:2308.07915 via the techniques used to construct a circuit for HGPCodes for Algorithm 2 in arXiv:2109.14609.

Let L and R denote, respectively, the data qubits addressed by the left and right half of the parity check matrix for X-type stabilizers (self.matrix_x). The sequence of subgraphs constructed here is as follows:

  1. Group together edges of the Tanner graph by XLA, XRB, ZLB, and ZRA type, where XLA, for

    example, refers to the edges associated for X-type parity checks that address data qubits in L, whose connections are determined by the polynomial A. The sequence of subgraphs (XLA, XRB, ZLB, ZRA) corresponds to a valid syndrome measurement circuit.

  2. Split A into two terms, A = A_1 + A_2, and correspondingly split the graphs XLA and

    ZRA into the pairs of graphs (XLA_1, XLA_2) and (ZRA_1, ZRA_2). Push XLA_1 to the end of the subgraph sequence for syndrome measurement, and push ZRA_1 to the beginning, thereby arriving at the final subgraph sequence (ZRA_1, XLA_2, XRB, ZLB, ZRA_2, XLA_1).

Pushing XLA_1 to the end of the subgraph sequence corresponds to commuting associated gates to the right of the syndrome measurement circuit. Similarly to the situation in Figure 2c of arXiv:2109.14609v1, commuting XLA_1 to the right of ZLB introduces CNOT gates between X and Z check qubits; the X and Z support of these gates is given, respectively, by the row and column of A_1 @ B.T. These CNOTs get cancelled out by pushing ZRA_1 to the left of XLB.

group: qldpc.abstract.AbelianGroup
orders: tuple[int, ...]
poly_a: sympy.Poly
poly_b: sympy.Poly
ring: qldpc.abstract.GroupRing
symbol_gens: dict[sympy.Symbol, qldpc.abstract.GroupMember]
symbols: tuple[sympy.Symbol, ...]
class qldpc.codes.quantum.QTCode(subset_a: collections.abc.Collection[qldpc.abstract.GroupMember], subset_b: collections.abc.Collection[qldpc.abstract.GroupMember], code_a: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], code_b: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | None = None, field: int | type[galois.FieldArray] | None = None, *, bipartite: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Quantum Tanner code: a CSS code for qudits defined on the faces of a Cayley complex.

Altogether, a quantum Tanner code is defined by:

  • two symmetric (self-inverse) subsets A and B of a group G, and

  • two classical codes C_A and C_B, respectively with block lengths |A| and |B|.

The qudits of a quantum Tanner code live on the faces of a Cayley complex built out of A and B. Each face of the Cayley complex looks like:

g ―――――――――― gb

f(g,a,b) |

ag ――――――――― agb

where (g,a,b) is an element of (G,A,B), and f(g,a,b) = {g, ag, gb, agb}. We define two (directed) subgraphs on the Cayley complex:

  • subgraph_x with edges ( g, f(g,a,b)), and

  • subgraph_z with edges (ag, f(g,a,b)).

The X-type parity checks of a quantum Tanner code are then given by the classical Tanner code on subgraph_x with subcode ~(C_A ⨂ C_B), where ~C is the dual code to C. Z-type parity checks are similarly given by the classical Tanner code on subgraph_z with subcode ~(~C_A ⨂ ~C_B).

Notes:

  • “Good” quantum Tanner code: projective special linear group and random classical codes.

References:

static get_subcodes(cayplex: qldpc.objects.CayleyComplex, code_a: qldpc.codes.common.ClassicalCode, code_b: qldpc.codes.common.ClassicalCode) → tuple[qldpc.codes.classical.TannerCode, qldpc.codes.classical.TannerCode][source]

Get the classical Tanner subcodes of a quantum Tanner code.

static get_subgraphs(cayplex: qldpc.objects.CayleyComplex) → tuple[qldpc._util.networkx.DiGraph, qldpc._util.networkx.DiGraph][source]

Build the subgraphs of the inner (classical) Tanner codes for a quantum Tanner code.

These subgraphs are defined using the faces of a Cayley complex. Each face looks like:

g ―――――――――― gb

f(g,a,b) |

ag ――――――――― agb

where f(g,a,b) = {g, ag, gb, agb}. Specifically, the (directed) subgraphs are:

  • subgraph_x with edges ( g, f(g,a,b)), and

  • subgraph_z with edges (ag, f(g,a,b)).

Classical Tanner codes on these subgraphs are used to construct a quantum Tanner code.

As a matter of practice, defining classical Tanner codes on subgraph_x and subgraph_z requires choosing an ordering on the edges incident to every source node of these graphs. If the group G is equipped with a total order, a natural ordering of edges incident to every source node is induced by assigning the label (a, b) to edge (g, f(g,a,b)). Consistency then requires that edge (ag, f(g,a,b)) has label (a^-1, b), as verified by defining g' = ag and checking that f(g,a,b) = f(g',a^-1,b).

static load(path: str) → QTCode[source]

Load a QTCode from a file.

static random(group: qldpc.abstract.Group, code_a: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], code_b: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | None = None, field: int | type[galois.FieldArray] | None = None, *, bipartite: bool = False, one_subset: bool = False, seed: int | None = None) → QTCode[source]

Construct a random quantum Tanner code from a base group and seed code(s).

If only one code C is provided, use its dual ~C for the second code.

save(path: str, *headers: str) → None[source]

Save the generating data of this code to a file.

code_a
code_b = None
complex: qldpc.objects.CayleyComplex
class qldpc.codes.quantum.QuantumGolayCode[source]

Bases: qldpc.codes.common.CSSCode

Quantum [[23, 1, 7]] Golay code, built from the classical [23, 12, 7] Golay code.

References:

class qldpc.codes.quantum.QuantumHammingCode(size: int, field: int | type[galois.FieldArray] | None = None, *, set_logicals: bool = True)[source]

Bases: qldpc.codes.common.CSSCode

Quantum Hamming code, whose parity check matrices are classical Hamming codes.

References:

class qldpc.codes.quantum.QuantumReedMullerCode(order: int, size: int)[source]

Bases: qldpc.codes.common.CSSCode

Self-orthogonal CSS code from a classical Reed-Muller code.

The code CSS(RM(r, m), RM(r, m)) is a [[2**m, 2**m - 2 * dim(RM(r, m)), 2**(r + 1)]] code for 0 <= r < (m - 1) / 2, i.e. whenever RM(r, m) is strictly self-orthogonal:

RM(r, m) ⊆ RM(r, m)⊥ = RM(m - r - 1, m).

The stabilizer generators are the rows of the generator matrix of RM(r, m), whose pairwise orthogonality follows from self-orthogonality. Both the X- and the Z-distance equal 2**(r + 1), the minimum weight of a vector in RM(m - r - 1, m) \ RM(r, m), attained by the indicator vector of an affine (r + 1)-flat in AG(m, 2) (MacWilliams & Sloane, Ch. 13). This closed form makes distance evaluation O(1), independent of block length.

References:

property order: int

The order parameter of this code.

property size: int

The size parameter of this code.

class qldpc.codes.quantum.SHPCode(code_a: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], code_b: qldpc.codes.common.ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]] | None = None, field: int | type[galois.FieldArray] | None = None, *, set_logicals: bool = True)[source]

Bases: qldpc.codes.common.CSSCode

Subsystem hypergraph product code.

A subsystem hypergraph product code (SHPCode) is constructed from two classical codes. Unlike the ordinary hypergraph product code, an SHPCode depends only on the actual classical codes it is built from; in particular, an SHPCode does not depend on the choice of parity check matrices for the underlying classical codes.

If the classical generating codes of an SHPCode have code parameters [n1, k1, d1] and [n2, k2, d2], the SHPCode has parameters [n1 n2, k1 k2, min(d1, d2)].

References:

static get_canonical_logical_line_ops(matrix_a: galois.FieldArray, matrix_b: galois.FieldArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Canonical logical line operators for a subsystem hypergraph product code.

These operators are essentially those in Theorem VIII.10 of arXiv:2502.07150v1, generalized slightly to account for the possibility that code_a != code_b.

static get_matrix_product(matrix_a: FieldOrRingArray, matrix_b: FieldOrRingArray) → tuple[FieldOrRingArray, FieldOrRingArray][source]

Subsystem hypergraph product of two parity check matrices.

code_a
code_b
class qldpc.codes.quantum.SHYPSCode(dim_x: int, dim_z: int | None = None, field: int | type[galois.FieldArray] | None = None, *, set_logicals: bool = True)[source]

Bases: SHPCode

Subsystem hypergraph product simplex (SHYPS) code.

Subsystem hypergraph product codes naturally inherit the automorphisms (symmetries) of the classical codes that they are built from. The SHYPSCode is built from classical SimplexCodes that have a very large automorphism group, which gives SHYPSCodes a large set of SWAP-transversal Clifford operations.

References:

class qldpc.codes.quantum.SLPCode(matrix_a: numpy.typing.NDArray[numpy.object_] | collections.abc.Sequence[collections.abc.Sequence[object]], matrix_b: numpy.typing.NDArray[numpy.object_] | collections.abc.Sequence[collections.abc.Sequence[object]] | None = None, *, set_logicals: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Subsystem lifted product code.

The subsystem lifted product code is a lifted version of the subsystem hypergraph product code. That is, the SLPCode is to the SHPCode what the LPCode is to the HGPCode. See help(qldpc.codes.LPCode) for additional information.

As an example, the SLPCode in example 1 on page 6 of https://arxiv.org/pdf/2404.18302v1 can be constructed by:

from qldpc.abstract import CyclicGroup, GroupRing, RingArray
from qldpc.codes import SLPCode

group = CyclicGroup(2)
ring = GroupRing(group)
x = ring.generators[0]  # generator of the cyclic group
matrix = RingArray.build([[1, x, x], [x, x, 1]], ring)  # Eq. 21 of arXiv:2404.18302v1
code = SLPCode(matrix)
assert code.get_code_params() == (18, 4, 2)

while the SLPCode in example 2 is:

group = CyclicGroup(3)
ring = GroupRing(group)
x = ring.generators[0]    # generator of the cyclic group, as a member of the ring
matrix = RingArray([[ring.one + x + x**2, ring.one + x, x]])  # Eq. 23 of arXiv:2404.18302v1
code = SLPCode(matrix)
assert code.get_code_params() == (27, 12, 2)

References:

static get_canonical_logical_line_ops(matrix_a: qldpc.abstract.RingArray, matrix_b: qldpc.abstract.RingArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Canonical logical line operators for a subsystem lifted product code.

static get_canonical_ring_logical_line_ops(matrix_a: qldpc.abstract.RingArray, matrix_b: qldpc.abstract.RingArray) → tuple[qldpc.abstract.RingArray, qldpc.abstract.RingArray][source]

Canonical ring-logical line operators for a subsystem lifted product code.

Generalizes SHPCode.get_canonical_logical_line_ops.

static to_lifted_logical_ops(logical_ops_x: qldpc.abstract.RingArray, logical_ops_z: qldpc.abstract.RingArray) → tuple[galois.FieldArray, galois.FieldArray][source]

Lift logical operators over a ring to logical operators over the base field.

matrix_a
matrix_b
class qldpc.codes.quantum.SteaneCode[source]

Bases: QuantumHammingCode

Smallest quantum error-correcting CSS code.

Also the smallest error-correcting color code.

References:

class qldpc.codes.quantum.SurfaceCode(rows: int, cols: int | None = None, field: int | type[galois.FieldArray] | None = None, *, rotated: bool = True)[source]

Bases: qldpc.codes.common.CSSCode

The one and only!

Actually, there are two variants: “ordinary” and “rotated” surface codes. The rotated code is more qubit-efficient.

References:

static get_rotated_checks(rows: int, cols: int) → tuple[numpy.typing.NDArray[numpy.int_], numpy.typing.NDArray[numpy.int_]][source]

Build X-sector and Z-sector parity check matrices.

Example 5x5 rotated surface code layout:

     ―――     ―――
    | ⋅ |   | ⋅ |
    ○―――○―――○―――○―――○―――
    | × | ⋅ | × | ⋅ | × |
 ―――○―――○―――○―――○―――○―――
| × | ⋅ | × | ⋅ | × |
 ―――○―――○―――○―――○―――○―――
    | × | ⋅ | × | ⋅ | × |
 ―――○―――○―――○―――○―――○―――
| × | ⋅ | × | ⋅ | × |
 ―――○―――○―――○―――○―――○
        | ⋅ |   | ⋅ |
         ―――     ―――

Here:

  • Circles (○) denote data qubits (of which there are 5×5 = 25 total).

  • Tiles with a cross (×) denote X-type parity checks (12 total).

  • Tiles with a dot (⋅) denote Z-type parity checks (12 total).

get_syndrome_subgraphs(*, strategy: str = 'smallest_last') → tuple[qldpc._util.networkx.DiGraph, ...][source]

Sequence of subgraphs of the Tanner graph that induces a syndrome extraction sequence.

See help(qldpc.codes.QuditCode.get_syndrome_subgraphs) for additional information.

If this is an unrotated surface code, return the syndrome subgraphs of the parent HGPCode. Otherwise, organize edges of the Tanner graph by an orientation in {NW, NE, SW, SE}, and by whether they are used for the readout of X-type or Z-type syndromes. Interleave these edges in such a way as to minimize circuit depth and avoid hook errors.

Parameters:

strategy – Only used if self.rotated is False, in which case this argument is passed to HGPCode.get_syndrome_subgraphs to color the edges of the Tanner graph of this code. Default: “smallest_last”.

cols = None
rotated = True
rows
class qldpc.codes.quantum.T4Code(matrix: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None, *, skip_validation: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Four-dimensional (2, 2) toric code.

A T4Code depends on a four-dimensional integer lattice. The lattice acts on Euclidean four-space by translations. The quotient manifold is a four-dimensional torus T^4. The number of physical qudits is 6 times the volume of the lattice. The number of logical qudits is the dimension of the 2nd homology group of T^4, which is 6.

Homologically, a T4Code is the topological CSS code attached to the 3-term sub-complex in the middle of the 5-term chain-complex

F[vertices] <- F[edges] <- F[faces] <- F[cubes] <- F[tesseracts]

of T^4 tiled by integer unit tesseracts. Cubes have 6 faces on the boundary, and edges are incident to 6 faces, so stabilizers have weight 6.

References:

chain
edges
face_basis = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
face_index
lattice_basis
num_cubes
num_edges
num_faces
num_vertices
class qldpc.codes.quantum.TBCode(matrix_a: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], matrix_b: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None, *, promise_equal_distance_xz: bool = False, skip_validation: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Two-block code.

A TBCode code is built out of two commuting matrices A and B, which are combined to define

  1. matrix_x = [A, B], and

  2. matrix_z = [B.T, -A.T].

Commutativity of A and B ensures that matrix_x @ matrix_z.T = AB - BA = 0, which makes matrix_x and matrix_z a valid choice of parity check matrices of a CSSCode.

Two-block codes constructed out of circulant matrices (i.e., matrices chosen from a ring over an abelian group) are known as quasi-cyclic codes (QCCodes).

References:

class qldpc.codes.quantum.TetrahedralCode(*, algebraic: bool = False)[source]

Bases: qldpc.codes.common.CSSCode

Smallest quantum error-correcting CSS code with a transversal non-Clifford (T) gate.

Also:

  • The smallest quantum error-correcting 3-D color code.

  • Often referred to as the [15, 1, 3] quantum Reed-Muller code.

Algebraically, a TetrahedralCode is a CSSCode built out of punctured Reed-Muller codes. Geometrically, a TetrahedralCode can be visualized with a tetrahedron (triangular pyramid).

Consider a tessellation of a tetrahedron into four identical polyhedra, or 3-cells, where each polyhedron is the convex hull of (a) a vertex of the tetrahedron, (b) the centers of the edges and faces incident to that vertex, and (c) the centroid of the tetrahedron. Qubits live on the vertices of these polyhedra. The stabilizers of the TetrahedralCode can be defined as follows:

  • Every 3-cell (polyhedron) is associated with an X-type stabilizer.

  • Every 2-cell (face of a polyhedron) is associated with a Z-type stabilizer.

Coloring the polyhedra red, green, blue, and yellow, the qubit layout for the TetrahedralCode can be visualized as follows:

        red
         0                           8
        / \                         / \
       /   \                       /   \
      2     4                    10     12                7
     / ‾‾6‾‾ \                   / ‾‾14‾ \
    /    |    \                 /    |    \              top
   1 --- 5 --- 3               9 --- 13 -- 11           vertex
    green  blue                                        (yellow)

vertices on the base     vertices in the "middle"
 of the tetrahedron     (edges, faces, and centroid)

The ordering of qubits is fixed by enforcing consistency between geometric and algebraic constructions of the TetrahedralCode.

See also Figure 2b of https://arxiv.org/pdf/2409.13465v2 for a nice picture, but note that

  1. The tetrahedral code in arXiv:2409.13465 swaps all X and Z operators.

  2. The TetrahedralCode defined here has a different qubit order. Specifically, qubit jj of the code defined here gets mapped to qubit kk = qubit_map[jj] of the code in 2409.13465, where qubit_map = [0, 10, 3, 14, 7, 13, 6, 8, 1, 9, 2, 12, 4, 11, 5].

A TetrahedralCode encodes one logical qubit.

  • The logical X operator can be defined on any _face_ of the tetrahedron.

  • The logical Z operator can be defined on any _edge_ of the tetrahedron.

References:

class qldpc.codes.quantum.ToricCode(rows: int, cols: int | None = None, field: int | type[galois.FieldArray] | None = None, *, rotated: bool = True)[source]

Bases: qldpc.codes.common.CSSCode

Surface code with periodic boundary conditions, encoding two logical qudits.

References:

static get_rotated_checks(rows: int, cols: int) → tuple[numpy.typing.NDArray[numpy.int_], numpy.typing.NDArray[numpy.int_]][source]

Build X-sector and Z-sector parity check matrices.

Same as in SurfaceCode.get_rotated_checks, but with periodic boundary conditions.

get_syndrome_subgraphs(*, strategy: str = 'smallest_last') → tuple[qldpc._util.networkx.DiGraph, ...][source]

Sequence of subgraphs of the Tanner graph that induces a syndrome extraction sequence.

If this is an unrotated toric code, return the syndrome subgraphs of the parent HGPCode. Otherwise, return the subgraphs of edges oriented along (NW, NE, SW, SE) directions.

Parameters:

strategy – Only used if self.rotated is False, in which case this argument is passed to HGPCode.get_syndrome_subgraphs to color the edges of the Tanner graph of this code. Default: “smallest_last”.

cols = None
rotated = True
rows
class qldpc.codes.quantum.TrivialCode(size: int, num_stabs_x: int = 0, num_stabs_z: int = 0, *, gauge_dimension: int = 0, self_dual: bool = False, field: int | type[galois.FieldArray] | None = None)[source]

Bases: qldpc.codes.common.CSSCode

The trivial code with single-qubit logical operators.

qldpc.codes.quantum.FieldOrRingArray