qldpc.codes.common

General error-correcting code classes and methods.

Attributes

Slice

Classes

AbstractCode

Base class for error-correcting codes.

CSSCode

QuditCode with separate X-type and Z-type parity checks.

ClassicalCode

Classical linear error-correcting code over a finite field F_q.

QuditCode

Quantum code for Galois qudits with dimension q = p^m for prime p and integer m.

Functions

get_random_array(→ galois.FieldArray)

Get a random array over a given finite field with a given shape.

get_scrambled_seed(→ int)

Scramble a seed, allowing us to safely increment seeds in repeat-until-success protocols.

Module Contents

class qldpc.codes.common.AbstractCode(matrix: AbstractCode | qldpc.math.IntegerArray | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None)[source]

Bases: abc.ABC

Base class for error-correcting codes.

abstractmethod canonicalized() → AbstractCode

The same code with its parity matrix in reduced row echelon form.

abstractmethod dimension() → int

The number of logical (qu)dits encoded by this code.

static equiv(code_a: AbstractCode, code_b: AbstractCode) → bool[source]

Are the two codes equivalent?

Do they have the same parity checks?

forget_distance() → Self[source]

Forget the known distance of this code.

graph() → qldpc._util.networkx.DiGraph

Tanner graph of this code.

static graph_to_matrix(graph: qldpc._util.networkx.DiGraph) → galois.FieldArray[source]
Abstractmethod:

Convert a Tanner graph into a parity check matrix.

is_equiv_to(other: AbstractCode) → bool[source]

Are the two codes equivalent?

Do they have the same parity checks?

matrix_as_string() → str[source]

The parity check matrix of this code as a string.

static matrix_to_graph(matrix: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]]) → qldpc._util.networkx.DiGraph[source]
Abstractmethod:

Convert a parity check matrix into a Tanner graph.

rank() → int

Rank of this code’s parity check matrix.

property field: type[galois.FieldArray]

Base field over which this code is defined.

property field_name: str

The name of the base field of this code.

property matrix: galois.FieldArray

Parity check matrix of this code.

property name: str

The name of this code.

property num_checks: int

Number of parity checks in this code.

class qldpc.codes.common.CSSCode(code_x: ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], code_z: ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None, *, is_subsystem_code: bool | None = None, promise_equal_distance_xz: bool = False)[source]

Bases: QuditCode

QuditCode with separate X-type and Z-type parity checks.

A CSSCode is defined from two classical codes with parity check matrices H_x and H_z, whose rows indicate, respectively, the support of X-type Pauli strings that witness Z-type errors, and Z-type Pauli strings that witness X-type errors. The full parity check matrix of a CSSCode is:

⌈ H_x,  0  ⌉
⌊  0 , H_z ⌋.

If all parity checks of a CSSCode commute, H_x @ H_z.T == 0, then the CSSCode is a stabilizer code; otherwise, the CSSCode is a subsystem code.

References:

canonicalized() → CSSCode

The same code with its parity matrices in reduced row echelon form.

static classical(code: ClassicalCode | numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], pauli: qldpc.objects.PauliXZ, field: int | type[galois.FieldArray] | None = None) → CSSCode[source]

Construct a CSSCode of only X-type or Z-type stabilizers.

static concatenate(outer: QuditCode, inner: QuditCode, inner_physical_to_outer_logical: collections.abc.Mapping[int, int] | collections.abc.Sequence[int] | None = None, *, inherit_logicals: bool = True) → CSSCode[source]

Concatenate two CSS codes.

The concatenated code uses the logical qudits of the “outer” code as the physical qudits of the “inner” code, with inner_physical_to_outer_logical defining the map from inner physical qudit index to outer logical qudit index.

This method nominally assumes that len(inner_physical_to_outer_logical) is equal to both the number of logical qudits of the outer code and the number of physical qudits of the inner code. If len(inner_physical_to_outer_logical) is larger than the number of outer logicals or inner physicals, then copies of the outer and inner codes are used (stacked together) to match the expected number of “intermediate” qudits. If no inner_physical_to_outer_logical mapping is provided, then this method “interleaves” intermediate qubits, using each logical qubit of an outer block as a physical qubit of a different inner code block.

If inherit_logicals is True, use the logical operators of the inner code as the logical operators of the concatenated code. Otherwise, logical operators of the concatenated code get recomputed from scratch.

conjugate() → CSSCode[source]

The same code with all X-type and Z-type operators swapped.

conjugated(qudits: slice | collections.abc.Sequence[int] | None = None) → QuditCode[source]

Apply local Fourier transforms, swapping X-type and Z-type operators.

Parameters:

qudits – The qudits to transform. If None, transform all qudits.

deformed(circuit: str | stim.Circuit, *, preserve_logicals: bool = False) → QuditCode[source]

Deform a qubit code by the given circuit.

Parameters:
  • circuit – The circuit to apply to the data qubits of this code.

  • preserve_logicals – If True, set the logical operators of the deformed code to those of the original code, throwing an error if the original logical operators are invalid for the deformed code. Default: False.

dual() → CSSCode[source]

The dual of this code, which swaps the roles of logical and gauge operators.

See help(qldpc.codes.QuditCode.dual) for an explanation.

static equiv(code_a: AbstractCode, code_b: AbstractCode) → bool[source]

Are the two codes equivalent?

Do they have the same parity checks?

forget_distance() → Self[source]

Forget the known distance of this code.

static from_qecdb_id(code_id: str) → CSSCode[source]

Retrieve a CSS code by ID from qecdb.org.

static from_strings(checks: collections.abc.Sequence[str], field: int | type[galois.FieldArray] | None = None) → QuditCode[source]

Construct a CSSCode from the provided parity checks.

Alias for QuditCode.from_strings(checks, field).to_css(). See help(QuditCode.from_strings).

get_code(pauli: qldpc.objects.PauliXZ) → ClassicalCode[source]

Retrieve the classical code of stabilizers of a given type.

get_destabilizer_ops(pauli: qldpc.objects.PauliXZ | None = None, *, symplectic: bool = False) → galois.FieldArray[source]

The destabilizers of this code.

See help(qldpc.codes.QuditCode.get_destabilizer_ops) for an explanation of destabilizers.

get_distance(pauli: qldpc.objects.PauliXZ | None = None, *, bound: int | bool | None = None, **bound_kwargs: Any) → int | float[source]

Compute (or upper bound) the minimum weight of nontrivial logical operators.

Parameters:
  • pauli – If passed qldpc.objects.Pauli.X, compute the X-distance (minimum weight of an X-type logical operator). If passed qldpc.objects.Pauli.Z, compute the Z-distance. If None (the default), minimize over X and Z.

  • bound – If False, 0, or None (the default), compute the exact code distance. Otherwise, compute an upper bound on code distance by minimizing over int(bound) independent randomized upper bounds; see help(get_distance_bound).

  • **bound_kwargs – Keyword arguments to pass to get_distance_bound.

Returns:

An integer distance (or bound) if it is defined, and np.nan otherwise.

get_distance_bound(num_trials: int = 1, pauli: qldpc.objects.PauliXZ | None = None, *, cutoff: int | None = None, **bound_kwargs: Any) → int | float[source]

Use a randomized algorithm to compute an upper bound on code distance.

If available (and appropriate, given the bound_kwargs), use GAP’s QDistRnd package to compute a distance bound. Otherwise, use the decoder-based algorithm in CSSCode.get_distance_bound_with_decoder.

Parameters:
  • num_trials – Minimize over this many independent upper bounds.

  • pauli – If passed qldpc.objects.Pauli.X, compute the X-distance (minimum weight of an X-type logical operator). If passed qldpc.objects.Pauli.Z, compute the Z-distance. If None (the default), minimize over X and Z.

  • cutoff – Exit early once the upper bound falls to or below this cutoff.

  • **bound_kwargs – Keyword arguments to pass to the downstream distance bounding method. If provided arguments that are not recognized by QDistRnd, use a decoder-based distance bounding method, and pass these keyword arguments to a decoder in a call to qldpc.decoders.get_decoder.

Returns:

An upper bound on distance if it is defined, or np.nan otherwise.

get_distance_bound_with_decoder(pauli: qldpc.objects.PauliXZ, num_trials: int = 1, *, cutoff: int | None = None, **decoder_kwargs: Any) → int | float[source]

Use a randomized algorithm to compute an upper bound on code distance.

Specifically, use the algorithm described in arXiv:2308.07915, also explained below.

Parameters:
  • pauli – If passed qldpc.objects.Pauli.X, compute the X-distance (minimum weight of an X-type logical operator). If passed qldpc.objects.Pauli.Z, compute the Z-distance.

  • num_trials – Minimize over this many independent upper bounds.

  • cutoff – Exit early once the upper bound falls to or below this cutoff.

  • **decoder_kwargs – Keyword arguments to pass to qldpc.decoders.get_decoder.

For ease of language, we henceforth assume without loss of generality that we are computing an X-distance, and tentatively assume that num_trials == 1.

Pick a random Z-type logical operator Z(w_z) whose support is indicated by the bitstring w_z. We now wish to find a low-weight Pauli-X string X(w_x) that

  1. has a trivial syndrome, and

  2. anti-commutes with Z(w_z),

which together would imply that X(w_x) is a nontrivial X-type logical operator. Mathematically, these conditions are equivalent to requiring that

  1. H_z @ w_x = 0, and

  2. w_z @ w_x = 1,

where H_z is the parity check matrix of the Z-type subcode that witnesses X-type errors.

Conditions (a) and (b) can be combined into the single block-matrix equation:

⌈ H_z   ⌉         ⌈ 0 ⌉
⌊ w_z.T ⌋ @ w_x = ⌊ 1 ⌋,

where the “0” on the top right is interpreted as a zero vector. This equation can be solved by decoding the syndrome [ 0, 0, ..., 0, 1 ].T for the parity check matrix [ H_z; w_z.T ]. If a decoder fails to find a solution, try again with a new random logical operator Z(w_z). If the decoder succeeds in finding a solution w_x, this solution corresponds to a logical X type operator X(w_x) – and presumably one of low Hamming weight, assuming that the decoder tries to find low-weight solutions to the decoding problem. The Hamming weight |w_x| is then our upper bound on the X-distance of this code.

In practice, we want to minimize over many randomized trials that compute an upper bound. To avoid constructing a new decoder for every trial, we set the effective parity check matrix to [ H_z; L_z ], where L_z is a matrix whose rows are a minimal basis for nontrivial logical Z-type operators. In each trial, we then construct an effective syndrome by enforcing that it has trivial stabilizers and that it anti-commutes with a random nonzero choice of the logical operators in L_z.

get_distance_exact(pauli: qldpc.objects.PauliXZ | None = None, *, cutoff: int = 1) → int | float[source]

Compute the minimum weight of nontrivial logical operators by brute force.

Parameters:
  • pauli – If passed qldpc.objects.Pauli.X, compute the X-distance (minimum weight of an X-type logical operator). If passed qldpc.objects.Pauli.Z, compute the Z-distance. If None (the default), minimize over X and Z.

  • cutoff – Exit and return once an upper bound on distance falls to or below this cutoff.

Returns:

An integer distance if it is defined, or np.nan otherwise.

get_distance_if_known(pauli: qldpc.objects.PauliXZ | None = None) → int | float | None[source]

Retrieve a distance, if known.

Otherwise, return None.

get_gauge_ops(pauli: qldpc.objects.PauliXZ | None = None, *, recompute: bool = False, symplectic: bool = False) → galois.FieldArray[source]

Basis of nontrivial logical Pauli operators for the gauge qudits of this code.

Nontrivial logical Pauli operators for the gauge qudits are organized similarly to the logical Pauli operators computed by CSSCode.get_logical_ops.

get_graph(pauli: qldpc.objects.PauliXZ) → qldpc._util.networkx.DiGraph[source]

Subgraph of the Tanner graph for pauli-type parity checks.

get_logical_error_rate_func(num_samples: int, max_error_rate: float = 0.1, pauli_bias: collections.abc.Sequence[float] | None = None, *, min_error_weight: int = 1, decoder_x_kwargs: dict[str, Any] | None = None, decoder_z_kwargs: dict[str, Any] | None = None, **decoder_kwargs: Any) → qldpc.codes.monte_carlo.ErrorRateFunc[source]

Construct a function from physical –> logical error rate in a code capacity model.

In addition to the logical error rate, the constructed function returns an uncertainty in that logical error rate: a posterior standard deviation covering statistical error alone (see help(qldpc.codes.ErrorRateFunc)).

The physical error rate provided to the constructed function is the probability with which each qubit experiences a Pauli error. The constructed function will throw an error if given a physical error rate larger than max_error_rate. If a pauli_bias is provided, it is treated as the relative probabilities of an X, Y, and Z error on each qubit; otherwise, these errors occur with equal probability, corresponding to a depolarizing error.

The logical error rate returned by the constructed function is the probability with which a code error (obtained by sampling independent errors on all qubits) is converted into a logical error by the decoder.

For a subsystem code, errors are decoded against the stabilizer generators of the code, so a syndrome has one entry per stabilizer generator. These generators can be high-weight (for example, the stabilizers of a Bacon-Shor code have weight proportional to the code’s linear size), which general-purpose decoders may handle poorly. The estimate is still computed correctly, but it can overestimate the logical error rate achievable with a decoder tailored to the code.

Errors of weight below min_error_weight are taken to be decoded perfectly and are not sampled; the claim is taken on trust. An error’s weight here is the number of qudits it acts on, so a single-qudit error has weight one whichever Pauli it applies.

Errors heavier than the sample budget could reach go unsampled and are all treated as failures, making the reported rate a high estimate by an amount the constructed function’s truncation_error_bound method reports. See help(qldpc.codes.ErrorRateFunc).

See help(qldpc.codes.ClassicalCode.get_logical_error_rate_func) for more details about how this method works.

get_logical_ops(pauli: qldpc.objects.PauliXZ | None = None, *, recompute: bool = False, symplectic: bool = False) → galois.FieldArray[source]

Basis of nontrivial logical Pauli operators for this code.

Logical operators are represented by a matrix logical_ops with shape (2 * k, 2 * n), where k and n are, respectively, the numbers of logical and physical qudits in this code. Each row of logical_ops is a vector that represents a logical operator. The first (respectively, second) n entries of this vector indicate the support of _physical_ X-type (respectively, Z-type) operators. Similarly, the first (second) k rows correspond to _logical_ X-type (Z-type) operators. The logical operators at rows j and j+k are dual to each other, which is to say that the logical operator at row j commutes with the logical operators in all other rows except row j+k.

If this method is passed a pauli operator (Pauli.X or Pauli.Z), it returns only the logical operators of that type. This matrix has shape (k, n) by default, but is expanded into a matrix with shape (k, 2 * n) if this method is called with symplectic=True.

Logical X-type operators only address physical qudits by physical X-type operators, and logical Z-type operators only address physical qudits by physical Z-type operators.

Logical operators are constructed with the method similar to that in Section 4.1 of Gottesman’s thesis (arXiv:9705052), generalized for subsystem qudit codes. The basic strategy is to fix the values of the logical operator matrix in the GL sector of the parity check matrix when written in standard form (see QuditCode.get_standard_form_data), and then fill in the remaining entries of the logical operator matrix as required by parity check constraints.

get_matrix(pauli: qldpc.objects.PauliXZ) → galois.FieldArray[source]

Retrieve the classical code of stabilizers of a given type.

get_stabilizer_ops(pauli: qldpc.objects.PauliXZ | None = None, *, canonicalized: bool = False, recompute: bool = False, symplectic: bool = False) → galois.FieldArray[source]

Basis of stabilizer group generators for this code.

If canonicalized is True, guarantee that the stabilizer matrix is canonicalized (i.e., row- reduced) such that its rows are a minimal generating set for the stabilizer group.

get_standard_form_data_xz() → tuple[numpy.typing.NDArray[numpy.int_], numpy.typing.NDArray[numpy.int_], numpy.typing.NDArray[numpy.int_], tuple[slice, slice, slice, slice], tuple[slice, Slice, Slice, slice, Slice, Slice]][source]

Construct the standard form X/Z parity check matrices with Gaussian elimination.

See help(qldpc.codes.QuditCode.get_standard_form_data) for additional information. The primary difference here is that this method returns the standard forms of matrix_x and matrix_z separately.

get_swel_logical_ops() → galois.FieldArray[source]

Find a self-dual basis of logical operators for this code: (Lx, Lz) = (L, L). Return L.

Raise a ValueError if no such basis exists (see QuditCode.is_swel).

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

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

The sequence here enforces that X-type stabilizers are read out before Z-type stabilizers. See help(qldpc.codes.QuditCode.get_syndrome_subgraphs) for additional information.

The ‘strategy’ argument to this method is only included for compatibility with QuditCode.get_syndrome_subgraphs.

matrix() → galois.FieldArray

Overall parity check matrix.

rank() → int

Rank of this code’s parity check matrix.

Equivalently, the number of linearly independent parity checks in this code.

reduce_logical_op(pauli: qldpc.objects.PauliXZ, logical_index: int, **decoder_kwargs: Any) → Self[source]

Reduce the weight of a logical operator.

A minimal-weight logical operator is found by enforcing that it has a trivial syndrome, and that it commutes with all logical operators except its dual. This is essentially the same method as that used in CSSCode.get_distance_bound.

reduce_logical_ops(pauli: qldpc.objects.PauliXZ | None = None, **decoder_kwargs: Any) → Self[source]

Reduce the weight of all logical operators.

set_logical_ops(logical_ops: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set CSS-form logical operators for this CSS code.

set_logical_ops_x(logicals_ops_x: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the X-type logical operators of this code.

Determine suitable Z-type logical operators automatically. This choice is unique mod stabilizers.

Let (Kx, Kz) and (Lx, Lz) denote the matrices of “old” and “new” logical operators of this code, each with shape (k, n). We know Kx, Kz, and Lx. To find a suitable choice of Lz, we write (1) Lz = M @ Kz for some basis-change matrix M in GL(k), and note that (2) Lz @ Lx.T = I_k. Here I_k is the k × k identity matrix.

Plugging (1) into (2), we find M = (Kz @ Lx.T)**-1, and in turn plug M into (1) to get Lz = (Kz @ Lx.T)**-1 @ Kz.

set_logical_ops_xz(logicals_ops_x: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], logicals_ops_z: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the logical operators of this code to the provided logical operators.

set_logical_ops_z(logicals_ops_z: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the Z-type logical operators of this code.

Determine suitable X-type logical operators automatically. This choice is unique mod stabilizers.

Let (Kx, Kz) and (Lx, Lz) denote the matrices of “old” and “new” logical operators of this code, each with shape (k, n). We know Kx, Kz, and Lz. To find a suitable choice of Lx, we write (1) Lx = M @ Kx for some basis-change matrix M in GL(k), and note that (2) Lx @ Lz.T = I_k. Here I_k is the k × k identity matrix.

Plugging (1) into (2), we find M = (Kx @ Lz.T)**-1, and in turn plug M into (1) to get Lx = (Kx @ Lz.T)**-1 @ Kx.

set_swel_logical_ops() → Self[source]

Set the logical operators of this code to those of a self-dual logical operator basis.

Raise a ValueError if this code is not SWEL (see QuditCode.is_swel).

static stack(codes: collections.abc.Sequence[QuditCode], inherit_logicals: bool = True) → CSSCode[source]

Stack the given CSS codes.

The stacked code is obtained by having the input codes act on disjoint sets of bits. Stacking two codes with parameters [n_1, k_1, d_1] and [n_2, k_2, d_2], for example, results in a single code with parameters [n_1 + n_2, k_1 + k_2, min(d_1, d_2)].

bias_tailoring_qubits: collections.abc.Sequence[int] | slice = ()
property code_x: ClassicalCode

The classical code of X-type parity checks.

property code_z: ClassicalCode

The classical code of Z-type parity checks.

property graph_x: qldpc._util.networkx.DiGraph

Subgraph of the Tanner graph for X-type parity checks.

property graph_z: qldpc._util.networkx.DiGraph

Subgraph of the Tanner graph for Z-type parity checks.

property is_self_dual: bool

Is this code self-dual?

That is, are its X-type and Z-type stabilizers equivalent?

property is_subsystem_code: bool

Is this code a subsystem code?

That is, do some parity checks fail to commute with each other?

property is_swel: bool

Is this code self-dual with equivalent logicals (SWEL)?

A SWEL code is a self-dual CSS code for which there exists a basis of logical operators (Lx, Lz) with Lx = Lz; that is, Hadamard-transforming any single-qudit logical Pauli X (in some logical Pauli basis) recovers the associated logical Pauli Z.

In the case of stabilizer (non-subsystem) codes over a field with characteristic 2 (that is, over GF(2**m), which includes qubits with m = 1), a self-dual CSS code is SWEL iff it has odd block length (Corollary 1 of arXiv:2503.19790), or at least one row of Lx (in any basis) has nonzero self-overlap (Theorem 1 of arXiv:2503.19790).

This method first checks special cases covered by arXiv:2503.19790, and otherwise directly checks the existence of a logical operator basis (Lx, Lz) with Lx = Lz.

property matrix_x: galois.FieldArray

X-type parity checks.

property matrix_z: galois.FieldArray

Z-type parity checks.

property num_checks: int

Number of parity checks in this code.

property num_checks_x: int

Number of X-type parity checks in this code.

property num_checks_z: int

Number of Z-type parity checks in this code.

class qldpc.codes.common.ClassicalCode(matrix: AbstractCode | qldpc.math.IntegerArray | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None)[source]

Bases: AbstractCode

Classical linear error-correcting code over a finite field F_q.

A classical binary code C = {x} is a set of vectors x (with entries in F_q) called code words. We consider only linear codes, for which any linear combination of code words is also code word.

Operationally, we define a classical code by a parity check matrix H with dimensions (num_checks, num_bits). Each row of H represents a linear constraint (a “check”) that code words must satisfy. A vector x is a code word iff H @ x = 0.

canonicalized() → ClassicalCode

The same code with its parity matrix in reduced row echelon form.

dimension() → int

The number of logical bits encoded by this code.

dual() → ClassicalCode[source]

Dual to this code.

The dual code ~C is the set of bitstrings orthogonal to C:

~C = { y : x @ y = 0 for all x in C }.

The generator of C (i.e., the matrix whose rows span C) is the parity check matrix of ~C.

static from_generator(generator: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None) → ClassicalCode[source]

Construct a ClassicalCode from a generator matrix.

static from_name(name: str) → ClassicalCode[source]

Named code in the GAP computer algebra system.

get_automorphism_group(*, with_magma: bool = False) → qldpc.abstract.Group[source]

Get the automorphism group of this code.

The automorphism group of a classical linear code is the group of permutations of bits that preserve the code space.

get_code_params(*, bound: int | bool | None = None, **bound_kwargs: Any) → tuple[int, int, int | float][source]

Compute the parameters of this code: [n,k,d].

Parameters:
  • bound – If False, 0, or None (the default), compute the exact code distance. Otherwise, compute an upper bound on code distance by minimizing over int(bound) independent randomized upper bounds; see help(get_distance_bound).

  • **bound_kwargs – Keyword arguments to pass to get_distance_bound.

Returns:

  • n is the number of data bits

  • k is the number of encoded (“logical”) bits

  • d is the code distance (or an upper bound on code distance).

Return type:

A tuple of integers, (n, k, d), where

get_distance(*, bound: int | bool | None = None, vector: collections.abc.Sequence[int] | numpy.typing.NDArray[numpy.int_] | None = None, **bound_kwargs: Any) → int | float[source]

Compute (or upper bound) the minimum Hamming weight of nontrivial code words.

Parameters:
  • bound – If False, 0, or None (the default), compute the exact code distance. Otherwise, compute an upper bound on code distance by minimizing over int(bound) independent randomized upper bounds; see help(get_distance_bound).

  • vector – If not None, rather than computing the code distance, compute the minimum Hamming distance between this vector and a code word. Default: None.

  • **bound_kwargs – Keyword arguments to pass to get_distance_bound.

Returns:

An integer distance (or bound) if it is defined, and np.nan otherwise.

get_distance_bound(num_trials: int = 1, *, cutoff: int | None = None, vector: collections.abc.Sequence[int] | numpy.typing.NDArray[numpy.int_] | None = None, **decoder_kwargs: Any) → int | float[source]

Use a randomized algorithm to compute an upper bound on code distance.

The code distance is the minimum Hamming distance between two code words, or equivalently the minimum Hamming weight of nonzero code words. To find a minimal nonzero code word we decode a trivial (all-0) syndrome, but enforce that the code word has nonzero overlap with a random word, which excludes the all-0 word as a candidate.

If bounding the minimum distance between a vector and a code word, we can interpret the vector as an error, and find a minimal-weight correction from decoding the syndrome induced by this vector.

Parameters:
  • num_trials – Minimize over this many independent upper bounds.

  • cutoff – Exit early once the upper bound falls to or below this cutoff.

  • vector – If not None, rather than computing the code distance, compute the minimum Hamming distance between this vector and a code word. Default: None.

  • **decoder_kwargs – Keyword arguments to pass to qldpc.decoders.get_decoder.

Returns:

An upper bound on distance if it is defined, or np.nan otherwise.

get_distance_exact(*, vector: collections.abc.Sequence[int] | numpy.typing.NDArray[numpy.int_] | None = None, cutoff: int = 1) → int | float[source]

Compute the minimum Hamming weight of nontrivial code words by brute force.

Parameters:
  • vector – If not None, rather than computing the code distance, compute the minimum Hamming distance between this vector and a code word. Default: None.

  • cutoff – Exit and return once an upper bound on distance falls to or below this cutoff.

Returns:

An integer distance if it is defined, or np.nan otherwise.

get_distance_if_known(vector: collections.abc.Sequence[int] | numpy.typing.NDArray[numpy.int_] | None = None) → int | float | None[source]

Retrieve a distance, or None if it is not known.

Parameters:

vector – If None (the default) retrieve the code distance. Otherwise, retrieve the minimum distance of this vector from a code word.

get_logical_error_rate_func(num_samples: int, max_error_rate: float = 0.1, *, min_error_weight: int = 1, **decoder_kwargs: Any) → qldpc.codes.monte_carlo.ErrorRateFunc[source]

Construct a function from physical –> logical error rate in a code capacity model.

Alongside the logical error rate, the constructed function returns an uncertainty in that rate: a posterior standard deviation covering statistical error alone. An error bar that also covers the errors too heavy for the sample budget to have reached is asymmetric, and should be drawn from max(value - error - func.truncation_error_bound(p), 0) up to value + error, because such errors are all treated as failures, which makes the rate a high estimate. See help(qldpc.codes.ErrorRateFunc).

If the decoder is known to correct every error of weight below min_error_weight, saying so skips sampling those weights and drops their contribution to the reported uncertainty, which otherwise dominates that uncertainty at small physical error rates while carrying no information. The claim is taken on trust and understates the reported failure or discard rate if it is false; it is a claim about the decoder rather than about the code, and cannot be read off the code distance. See help(qldpc.codes.ErrorRateFunc) for the full caveats.

The physical error rate provided to the constructed function is the probability with which each bit experiences a bit-flip error. The constructed function will throw an error if given a physical error rate larger than max_error_rate.

The logical error rate returned by the constructed function is the probability with which a code error (obtained by sampling independent errors on all bits) is decoded incorrectly.

The basic idea in this method is to think of the fidelity

F(p) = 1 - logical_error_rate(p)

as a function of the physical error rate p, and decompose

F(p) = sum_k q_k(p) F_k,

where

q_k(p) = (n choose k) p**k (1-p)**(n-k)

is the probability of a weight-k error (here n is total number of bits in the code), and F_k is the probability with which a weight-k error is corrected by the decoder. Importantly, F_k is independent of p. We therefore use our sample budget to compute estimates of F_k (according to some allocation of samples to each weight k, which depends on the max_error_rate), and then recycle the values of F_k to compute each F(p).

There is one more minor trick, which is that we can use the fact that F_0 = 1 to simplify

F(p) = q_0(p) + sum_(k>0) q_k(p) F_k.

We thereby only need to sample errors of weight k > 0, or of weight k >= min_error_weight when a caller sets that higher, since F_k = 1 for every weight declared to be decoded perfectly. The sum runs only as far as the heaviest weight the budget reached, and F_k = 0 is assumed above that.

get_random_word(*, seed: int | None = None) → galois.FieldArray[source]

Random code word: a sum of all generating words with random field coefficients.

get_weight() → int[source]

Compute the weight of the largest parity check.

static graph_to_matrix(graph: qldpc._util.networkx.DiGraph) → galois.FieldArray[source]

Convert a Tanner graph into a parity check matrix.

iter_words(skip_zero: bool = False) → collections.abc.Iterator[galois.FieldArray][source]

Iterate over the code words of this code.

static matrix_to_graph(matrix: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]]) → qldpc._util.networkx.DiGraph[source]

Convert a parity check matrix into a Tanner graph.

The Tanner graph is a bipartite graph with (num_checks, num_bits) vertices, respectively identified with the checks and bits of the code. The check vertex c and the bit vertex b share an edge iff c addresses b; that is, edge (c, b) is in the graph iff H[c, b] != 0.

A check that addresses no bits, as an all-zero row of H defines, is an isolated vertex of the graph. Seeding a vertex for every row puts the check vertices in one-to-one correspondence with the rows of H, so the graph records how many checks there are even when some of them address no bits.

puncture(bits: collections.abc.Collection[int]) → ClassicalCode[source]

Deprecated alias for ClassicalCode.punctured.

punctured(bits: collections.abc.Collection[int]) → ClassicalCode[source]

Delete the specified bits from a code.

To delete bits from a code, we can remove the corresponding columns from its generator matrix (whose rows form a basis for the code space).

Puncturing a code is equivalent to shortening its dual code (Prop. 2.5 of arXiv:2308.15746). Shortening a code at a bit keeps only the code words that are zero at that bit. To shorten a code at a bit, we can (1) row-reduce the generator matrix at that bit, (2) delete the pivot row for that bit, and then (3) delete the column for that bit.

Since we represent codes by their parity check matrices, it’s computationally cheaper for us to modify parity check matrices (without converting to/from generator matrices). Altogether, we puncture this code by shortening its dual code, applying the shortening steps above to the parity check matrix of the code.

static random(bits: int, checks: int, field: int | type[galois.FieldArray] | None = None, *, seed: int | None = None) → ClassicalCode[source]

Construct a random linear code with the given number of bits and checks.

Reject any code with trivial checks or unchecked bits, identified by an all-zero row or column in the code’s parity check matrix.

rank() → int

Rank of this code’s parity check matrix.

set_generator(generator: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]]) → Self[source]

Set the generator matrix of this code.

shorten(bits: collections.abc.Collection[int]) → ClassicalCode[source]

Deprecated alias for ClassicalCode.shortened.

shortened(bits: collections.abc.Collection[int]) → ClassicalCode[source]

Shorten a code to the words that are zero on the specified bits, and delete those bits.

Shortening a code is equivalent to puncturing the dual code; see the docstring for ClassicalCode.punctured for additional information.

Altogether, to shorten this code at the given bits, we remove the corresponding columns from its parity check matrix.

static stack(codes: collections.abc.Sequence[ClassicalCode]) → ClassicalCode[source]

Stack the given classical codes.

The stacked code is obtained by having the input codes act on disjoint sets of bits. Stacking two codes with parameters [n_1, k_1, d_1] and [n_2, k_2, d_2], for example, results in a single code with parameters [n_1 + n_2, k_1 + k_2, min(d_1, d_2)].

static tensor_product(code_a: ClassicalCode, code_b: ClassicalCode) → ClassicalCode[source]

Tensor product C_a ⨂ C_b of two codes C_a and C_b.

Let G_a and G_b respectively denote the generators C_a and C_b. Definition: C_a ⨂ C_b is the code whose generators are G_a ⨂ G_b.

Observation: G_a ⨂ G_b is the check matrix of ~(C_a ⨂ C_b). We therefore construct ~(C_a ⨂ C_b) and return its dual ~~(C_a ⨂ C_b) = C_a ⨂ C_b.

property generator: galois.FieldArray

a matrix whose rows form a basis for all code words.

Type:

Generator of this code

property num_bits: int

Number of data bits in this code.

class qldpc.codes.common.QuditCode(matrix: AbstractCode | qldpc.math.IntegerArray | collections.abc.Sequence[collections.abc.Sequence[int]], field: int | type[galois.FieldArray] | None = None, *, is_subsystem_code: bool | None = None)[source]

Bases: AbstractCode

Quantum code for Galois qudits with dimension q = p^m for prime p and integer m.

A QuditCode is initialized from a parity check matrix H whose rows represent Pauli strings. If all of these Pauli strings commute, then the QuditCode is a stabilizer code, and the rows of H are generators of the code’s stabilizer group. Otherwise, the QuditCode is a subsystem code, which is equivalent to a stabilizer code in which some logical qudits are promoted to “gauge qudits”. In this case, the rows of H are generators of the code’s gauge group.

More specifically, for a QuditCode with block length num_qudits, each row of H is a symplectic vector P = [P_x|P_z] of length 2 * num_qudits, where each of P_x and P_z are vectors of length num_qudits that indicate the support of X-type and Z-type Pauli operators on the physical qudits of the QuditCode. If P_x[j] = r_x and P_z[j] = r_z, where r_x and r_z are elements of the Galois field GF(q) (for example, GF(2) ~ {0, 1} for qubits), then the Pauli string P addresses physical qudit j by the qudit operator X(r_x) Z(r_z), where

  • X(r) = sum_{k=0}^{q-1} |k+r><k| is a shift operator, and

  • Z(r) = sum_{k=0}^{q-1} w^{k r} |k><k| is a phase operator, with w = exp(2 pi i / q).

Here r and k are not integers, but elements of the Galois field GF(q), which has special rules for addition and multiplication when q is not a prime number.

The matrix H is a “parity check matrix” in the sense that its null space with respect to the symplectic inner product ⟨P,Q⟩_s = P_x @ Q_z - P_z @ Q_x = P @ symplectic_conjugate(Q) is the space of logical Pauli operators of the QuditCode.

References:

canonicalized() → QuditCode

The same code with its parity matrix in reduced row echelon form.

static concatenate(outer: QuditCode, inner: QuditCode, inner_physical_to_outer_logical: collections.abc.Mapping[int, int] | collections.abc.Sequence[int] | None = None, *, inherit_logicals: bool = True) → QuditCode[source]

Concatenate two qudit codes.

The concatenated code uses the logical qudits of the “outer” code as the physical qudits of the “inner” code, with inner_physical_to_outer_logical defining the map from inner physical qudit index to outer logical qudit index.

This method nominally assumes that len(inner_physical_to_outer_logical) is equal to both the number of logical qudits of the outer code and the number of physical qudits of the inner code. If len(inner_physical_to_outer_logical) is larger than the number of outer logicals or inner physicals, then copies of the outer and inner codes are used (stacked together) to match the expected number of “intermediate” qudits. If no inner_physical_to_outer_logical mapping is provided, then this method “interleaves” intermediate qubits, using each logical qubit of an outer block as a physical qubit of a different inner code block.

If inherit_logicals is True, use the logical operators of the inner code as the logical operators of the concatenated code. Otherwise, logical operators of the concatenated code get recomputed from scratch.

conjugate() → QuditCode[source]

The same code with all X-type and Z-type operators swapped.

conjugated(qudits: slice | collections.abc.Sequence[int] | None = None) → QuditCode[source]

Apply local Fourier transforms, swapping X-type and Z-type operators.

Parameters:

qudits – The qudits to transform. If None, transform all qudits.

deformed(circuit: str | stim.Circuit, *, preserve_logicals: bool = False) → QuditCode[source]

Deform a qubit code by the given circuit.

Parameters:
  • circuit – The circuit to apply to the data qubits of this code.

  • preserve_logicals – If True, set the logical operators of the deformed code to those of the original code, throwing an error if the original logical operators are invalid for the deformed code. Default: False.

dimension() → int

The number of logical qudits encoded by this code.

dual() → QuditCode[source]

Dual to this code, which swaps the roles of logical and gauge operators.

The dual of a quantum code is defined almost identically to the dual a classical code.

In the classical case, a code C is defined as a set of bitstrings, { x : x in C }. The dual code ~C is then the set of bitstrings that are orthogonal to C:

~C = { y : x @ y = 0 for all x in C }.

This definition is equivalent to saying that the generator of C (a matrix whose rows span C) is the parity check matrix of ~C, and vice versa.

To analogously define the dual of a quantum code, we need to: (1) Represent Pauli strings by symplectic vectors that indicate the support of

(single-qudit) X and Z Pauli operators.

  1. Replace the ordinary inner product x @ y by the symplectic inner product,

    x @ symplectic_conjugate(y), which is zero iff x and y represent a pair of Pauli strings that commute.

A quantum code C can be defined as the set of all symplectic vectors that represent the logical Pauli operators of the code. The dual code ~C is then

~C = { y : x @ symplectic_conjugate(y) = 0 for all x in C }.

In words, the dual code consists of all operators that commute with the logical operators of the original code. The logical operators of the dual code are therefore the stabilizers and gauge operators of the original code.

static from_qecdb_id(code_id: str) → QuditCode[source]

Retrieve a code by ID from qecdb.org.

static from_strings(checks: collections.abc.Sequence[str], field: int | type[galois.FieldArray] | None = None) → QuditCode[source]

Construct a QuditCode from the provided parity checks.

Strings such as “Z_YX” and “Z I Y X” are both recognized, but a string like “ZI Y X” is not.

Pauli-X/Y/Z operators for qudit codes with field > 2 must be annotated by an element of the Galois field GF(field), such as “Z(1) _ Y(3) X(2)”. In this case “Y(a)” is an alias for “X(a)*Z(a)”, and strings such as “Z(1) _ X(1)*Z(3) X(2)” are also valid.

gauge_dimension() → int

The number of gauge qudits in this code.

get_code_params(*, bound: int | bool | None = None, **bound_kwargs: Any) → tuple[int, int, int | float][source]

Compute the parameters of this code: [n,k,d].

Parameters:
  • bound – If False, 0, or None (the default), compute the exact code distance. Otherwise, compute an upper bound on code distance by minimizing over int(bound) independent randomized upper bounds; see help(get_distance_bound).

  • **bound_kwargs – Keyword arguments to pass to get_distance_bound.

Returns:

  • n is the number of data qudits

  • k is the number of encoded (“logical”) qudits

  • d is the code distance (or an upper bound on code distance).

Return type:

A tuple of integers, (n, k, d), where

get_destabilizer_ops(pauli: qldpc.objects.PauliXZ | None = None, *, symplectic: bool = True) → galois.FieldArray[source]

The destabilizers of this code.

Destabilizers are defined relative to a specific minimal choice of stabilizer generators. This method first considers the stabilizer matrix built by self.get_stabilizer_ops(). If that choice is overcomplete, this method uses self.get_stabilizer_ops(canonicalized=True).

If a pauli (Pauli.X or Pauli.Z) is provided, return only the destabilizers whose leading (first nonzero) entry has that type. Since each destabilizer anticommutes with the single stabilizer generator it is paired with, these are the destabilizers dual to the stabilizer generators of the opposite type: Pauli.X selects the destabilizers dual to the Z-type stabilizers, and Pauli.Z those dual to the X-type stabilizers.

The symplectic argument is provided for compatibility with CSSCode.get_destabilizer_ops, and must always be True for a non-CSS code.

get_distance(*, bound: int | bool | None = None, **bound_kwargs: Any) → int | float[source]

Compute (or upper bound) the minimum weight of nontrivial logical operators.

Parameters:
  • bound – If False, 0, or None (the default), compute the exact code distance. Otherwise, compute an upper bound on code distance by minimizing over int(bound) independent randomized upper bounds; see help(get_distance_bound).

  • **bound_kwargs – Keyword arguments to pass to get_distance_bound.

Returns:

An integer distance (or bound) if it is defined, and np.nan otherwise.

get_distance_bound(num_trials: int = 1, *, cutoff: int | None = None, **bound_kwargs: Any) → int | float[source]

Use a randomized algorithm to compute an upper bound on code distance.

Specifically, use GAP’s QDistRnd package to compute a distance bound. Raise an error otherwise.

Parameters:
  • num_trials – Minimize over this many independent upper bounds.

  • cutoff – Exit early once the upper bound falls to or below this cutoff.

  • **bound_kwargs – Keyword arguments to pass to the downstream distance bounding method. See https://qec-pages.github.io/QDistRnd/doc/chap4.html.

Returns:

An upper bound on distance if it is defined, or np.nan otherwise.

get_distance_exact(*, cutoff: int = 1) → int | float[source]

Compute the minimum weight of nontrivial logical operators by brute force.

Parameters:

cutoff – Exit and return once an upper bound on distance falls to or below this cutoff.

Returns:

An integer distance if it is defined, or np.nan otherwise.

get_distance_if_known() → int | float | None[source]

Retrieve a distance, if known.

Otherwise, return None.

get_dual_subsystem_code() → QuditCode[source]

Deprecated alias for self.dual().

get_gauge_ops(pauli: qldpc.objects.PauliXZ | None = None, *, symplectic: bool = True) → galois.FieldArray[source]

Basis of nontrivial logical Pauli operators for the gauge qudits of this code.

Nontrivial logical Pauli operators for the gauge qudits are organized similarly to the logical Pauli operators computed by QuditCode.get_logical_ops.

The symplectic argument is provided for compatibility with CSSCode.get_gauge_ops, and must always be True for a non-CSS code.

get_logical_error_rate_func(num_samples: int, max_error_rate: float = 0.1, pauli_bias: collections.abc.Sequence[float] | None = None, *, min_error_weight: int = 1, **decoder_kwargs: Any) → qldpc.codes.monte_carlo.ErrorRateFunc[source]

Construct a function from physical –> logical error rate in a code capacity model.

In addition to the logical error rate, the constructed function returns an uncertainty in that logical error rate: a posterior standard deviation covering statistical error alone (see help(qldpc.codes.ErrorRateFunc)).

The physical error rate provided to the constructed function is the probability with which each qubit experiences a Pauli error. The constructed function will throw an error if given a physical error rate larger than max_error_rate. If a pauli_bias is provided, it is treated as the relative probabilities of an X, Y, and Z error on each qubit; otherwise, these errors occur with equal probability, corresponding to a depolarizing error.

The logical error rate returned by the constructed function is the probability with which a code error (obtained by sampling independent errors on all qubits) is converted into a logical error by the decoder.

For a subsystem code, errors are decoded against the stabilizer generators of the code, so a syndrome has one entry per stabilizer generator. These generators can be high-weight (for example, the stabilizers of a Bacon-Shor code have weight proportional to the code’s linear size), which general-purpose decoders may handle poorly. The estimate is still computed correctly, but it can overestimate the logical error rate achievable with a decoder tailored to the code.

Errors of weight below min_error_weight are taken to be decoded perfectly and are not sampled; the claim is taken on trust. An error’s weight here is the number of qudits it acts on, so a single-qudit error has weight one whichever Pauli it applies.

Errors heavier than the sample budget could reach go unsampled and are all treated as failures, making the reported rate a high estimate by an amount the constructed function’s truncation_error_bound method reports. See help(qldpc.codes.ErrorRateFunc).

See help(qldpc.codes.ClassicalCode.get_logical_error_rate_func) for more details about how this method works.

get_logical_ops(pauli: qldpc.objects.PauliXZ | None = None, *, recompute: bool = False, symplectic: bool = True) → galois.FieldArray[source]

Basis of nontrivial logical Pauli operators for this code.

Logical operators are represented by a matrix logical_ops with shape (2 * k, 2 * n), where k and n are, respectively, the numbers of logical and physical qudits in this code. Each row of logical_ops is a vector that represents a logical operator. The first (respectively, second) n entries of this vector indicate the support of _physical_ X-type (respectively, Z-type) operators. Similarly, the first (second) k rows correspond to _logical_ X-type (Z-type) operators. The logical operators at rows j and j+k are dual to each other, which is to say that the logical operator at row j commutes with the logical operators in all other rows except row j+k.

If this method is passed a pauli operator (Pauli.X or Pauli.Z), it returns only the logical operators of that type.

For a non-subsystem code, logical X-type operators have X-support and may additionally have Z-support, while logical Z-type operators have only Z-support and no X-support. These logical operators are constructed with a method similar to that in Section 4.1 of Gottesman’s thesis (arXiv:9705052): fix the values of the logical operator matrix in the GL sector of the parity check matrix when written in standard form (see QuditCode.get_standard_form_data), and fill in the remaining entries of the logical operator matrix as required by commutation constraints.

For a subsystem code, logical operators are constructed as a symplectic basis of the gauge group’s centralizer, whose symplectic radical is the stabilizer group. These logical operators make no guarantees on their physical support.

The symplectic argument is provided for compatibility with CSSCode.get_logical_ops, and must always be True for a non-CSS code.

get_stabilizer_ops(pauli: qldpc.objects.PauliXZ | None = None, *, canonicalized: bool = False, recompute: bool = False, symplectic: bool = True) → galois.FieldArray[source]

Basis of stabilizer group generators for this code.

If canonicalized is True, guarantee that the stabilizer matrix is canonicalized (i.e., row reduced) such that its rows are a minimal generating set for the stabilizer group.

The symplectic argument is provided for compatibility with CSSCode.get_stabilizer_ops, and must always be True for a non-CSS code.

get_standard_form_data() → tuple[numpy.typing.NDArray[numpy.int_], numpy.typing.NDArray[numpy.int_], tuple[slice, slice, slice, slice], tuple[slice, Slice, Slice, slice, Slice, Slice]][source]

Construct the standard form of the parity check matrix with Gaussian elimination.

The standard form of the parity check is the block matrix:

⌈  I   ·   ·   ·  |  ·   ·   ·   ·  ⌉ S_X --> rows_sx (X-type stabilizers)
|      ·   I   ·  |  ·   ·   ·   ·  | G_X --> rows_gx (X-type gauge ops)
|                 |  ·   I   ·   ·  | S_Z --> rows_sz (Z-type stabilizers)
⌊                 |  ·       I   ·  ⌋ G_Z --> rows_gz (Z-type gauge ops)
  S_X S_Z G_X L_X   S_X S_Z G_Z L_Z
   |   |   |   |     |   |   |   |
   |   |   |   |     |   |   |   └----------> cols_lz (~ number of logical qudits)
   |   |   |   |     |   |   └--------------> cols_gz (Z-type gauge pivots)
   |   |   |   |     |   └------------------> cols_sz (Z-type stabilizer pivots)
   |   |   |   |     └----------------------> cols_sx (X-type stabilizer pivots)
   |   |   |   └----------------------------> cols_lx (~ number of logical qudits)
   |   |   └--------------------------------> cols_gx (X-type gauge pivots)
   |   └------------------------------------> cols_sz (Z-type stabilizer pivots)
   └----------------------------------------> cols_sx (X-type stabilizer pivots)

Here I is an identity matrix of an appropriate size, and dots (·) indicate nonzero blocks of the matrix. Each row sector is associated with sets of linearly independent stabilizers or gauge operators, though the gauge operators are generally not necessarily sorted into conjugate pairs (as in self.get_gauge_ops() and self.get_logical_ops()).

For convenience, the standard-form matrix is returned with shape (-1, 2, len(self)), such that, for example, matrix[r, 1, :] indicates the Pauli-Z support of parity check r.

In addition to the standard-form matrix, this method returns a 1-D array qudit_locs, for which qudit_locs[j] is the location of qudit j in the standard-form matrix. The original parity check matrix (modulo elementary row operations and array reshaping) is matrix[:, :, np.argsort(qudit_locs)]. As a sanity check, the following test should pass:

matrix_2d = matrix[:, :, np.argsort(qudit_locs)].reshape(-1, 2 * len(self))
assert np.array_equal(matrix_2d.row_space(), self.canonicalized.matrix)

Finally, this method also returns slices (index sets) for all row and column sectors, which enables selecting blocks of the parity check matrix with, say, matrix[rows_sx, 1, cols_lz].

One subtlety to note is that columns of the standard-form matrix may not be in the same order as that suggested by the visualization above, but blocks retrieved by the index sets are guaranteed to be consistent with the placement of identity matrices, which is to say that each of:

matrix[rows_sx, 0, cols_sx]
matrix[rows_gx, 0, cols_gx]
matrix[rows_sz, 1, cols_sz]
matrix[rows_gz, 1, cols_gz]

is guaranteed to be an identity matrix.

get_strings() → list[str][source]

Parity checks checks of this code, represented by strings.

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.

This contract is defined only for stabilizer codes. Subsystem-code gauge checks need a separate gauge-fixing schedule and therefore are rejected explicitly.

Every edge of the Tanner graph is associated with a two-qubit gate that needs to be applied to “write” parity checks onto ancilla qubits (i.e., for syndrome extraction). The sequence of subgraphs returned by this method induces a (possibly partial) ordering on these gates, which is used by qldpc.circuits.EdgeColoring to construct a syndrome measurement circuit.

Subclasses of QuditCode can override this method to define a code-specific syndrome measurement sequence, so long as the following requirements are satisfied:

  1. Any pair of subgraphs must be edge-disjoint.

  2. Every edge of the Tanner graph of the code must belong to one of the subgraphs. Vertices need not be covered: an isolated vertex, be it a check that addresses no qudits or a qudit that no check addresses, has no two-qubit gate to schedule.

  3. For every subgraph, all two-qubit gates associated with its edges must commute.

  4. The sequence of subgraphs must correspond to a valid syndrome extraction circuit.

The sequence here colors parity checks in such a way that any two parity checks with overlapping support have different colors. Each color induces a subgraph of all edges incident to that color. These subgraphs are returned in arbitrary order.

Parameters:

strategy – The strategy used by nx.greedy_color to color parity checks. Default: “smallest_last”.

get_weight() → int[source]

Compute the weight of the largest parity check.

static graph_to_matrix(graph: qldpc._util.networkx.DiGraph) → galois.FieldArray[source]

Convert a Tanner graph into a parity check matrix.

static matrix_to_graph(matrix: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]]) → qldpc._util.networkx.DiGraph[source]

Convert a parity check matrix into a Tanner graph.

A check that addresses no qudits, as an all-zero row defines, is an isolated vertex of the graph. Seeding a vertex for every row puts the check vertices in one-to-one correspondence with the rows, so the graph records how many checks there are even when some of them address no qudits.

maybe_to_css() → QuditCode[source]

Try to convert this QuditCode into a CSSCode.

Return self if we fail.

maybe_to_swel() → QuditCode[source]

Try to convert this QuditCode into a CSSCode with SWEL logical operators.

Return self if we fail.

set_logical_ops(logical_ops: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the logical operators of this code to the provided logical operators.

set_logical_ops_x(logicals_ops_x: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the X-type logical operators of this code.

Determine suitable Z-type logical operators automatically. This choice is unique mod stabilizers.

Let (Kx, Kz) and (Lx, Lz) denote the matrices of “old” and “new” logical operators of this code, each with shape (k, 2*n). We know Kx, Kz, and Lx. To find a suitable choice of Lz, we write (1) Lz = M @ Kz for some basis-change matrix M in GL(k), and note that (2) Lz @ Ω.T @ Lx.T = I_k. Here Ω is the symplectic form, and I_k is the k × k identity matrix.

Plugging (1) into (2), we find M = (Kz @ Ω.T @ Lx.T)**-1, and in turn plug M into (1) to get Lz = (Kz @ Ω.T @ Lx.T)**-1 @ Kz.

The X-type logical operators are given by a matrix with shape (k, 2*n). As a convenience, a matrix with shape (k, n) is also accepted, in which case its entries are taken to be the X-type support of X-only logical operators (that is, with zero Z-type support).

set_logical_ops_z(logicals_ops_z: numpy.typing.NDArray[numpy.int_] | collections.abc.Sequence[collections.abc.Sequence[int]], *, skip_validation: bool = False) → Self[source]

Set the Z-type logical operators of this code.

Determine suitable X-type logical operators automatically. This choice is unique mod stabilizers.

Let (Kx, Kz) and (Lx, Lz) denote the matrices of “old” and “new” logical operators of this code, each with shape (k, 2*n). We know Kx, Kz, and Lz. To find a suitable choice of Lx, we write (1) Lx = M @ Kx for some basis-change matrix M in GL(k), and note that (2) Lx @ Ω @ Lz.T = I_k. Here Ω is the symplectic form, and I_k is the k × k identity matrix.

Plugging (1) into (2), we find M = (Kx @ Ω @ Lz.T)**-1, and in turn plug M into (1) to get Lx = (Kx @ Ω @ Lz.T)**-1 @ Kx.

The Z-type logical operators are given by a matrix with shape (k, 2*n). As a convenience, a matrix with shape (k, n) is also accepted, in which case its entries are taken to be the Z-type support of Z-only logical operators (that is, with zero X-type support).

static stack(codes: collections.abc.Sequence[QuditCode], inherit_logicals: bool = True) → QuditCode[source]

Stack the given qudit codes.

The stacked code is obtained by having the input codes act on disjoint sets of bits. Stacking two codes with parameters [n_1, k_1, d_1] and [n_2, k_2, d_2], for example, results in a single code with parameters [n_1 + n_2, k_1 + k_2, min(d_1, d_2)].

to_css() → CSSCode[source]

Try to convert this QuditCode into a CSSCode.

Throw an error if we fail.

to_swel() → CSSCode[source]

Convert this QuditCode into a CSSCode with SWEL logical operators.

Throw an error if we fail.

property is_subsystem_code: bool

Is this code a subsystem code?

That is, do some parity checks fail to commute with each other?

property num_qubits: int

Number of data qubits in this code.

property num_qudits: int

Number of data qudits in this code.

qldpc.codes.common.get_random_array(field: type[galois.FieldArray], shape: int | tuple[int, ...], *, satisfy: collections.abc.Callable[[galois.FieldArray], bool | numpy.bool_] = lambda _: ..., seed: int | None = None) → galois.FieldArray[source]

Get a random array over a given finite field with a given shape.

If passed a condition that the array must satisfy, re-sample until the condition is met.

qldpc.codes.common.get_scrambled_seed(seed: int) → int[source]

Scramble a seed, allowing us to safely increment seeds in repeat-until-success protocols.

qldpc.codes.common.Slice