Skip to main content
IBM Quantum Platform

bit_flip_checks

qiskit_addon_utils.noise_management.bit_flip_checks

Functions and classes for post-selection via circuit bit-flip checks.

PostSelectionSummary

class PostSelectionSummary(primary_cregs, measure_map, edges, *, measure_map_ps=None, measure_map_pre=None, post_check_suffix='_ps', pre_check_suffix='_pre', spectator_cregs=None)

GitHub

Bases: object

A helper class to store the properties of a quantum circuit required to postselect based on bit-flip checks.

Initialize a PostSelectionSummary object.

Parameters

  • primary_cregs (set[str]) – The names of the “primary” classical registers, namely those that do not end with the pre- and post-circuit check suffixes.
  • measure_map (dict[int, tuple[str, int]]) – A map between qubit indices to the register and clbits that uniquely define a measurement on those qubits (primary measurements).
  • edges (set[frozenset[int]]) – A list of tuples defining pairs of neighboring qubits.
  • measure_map_ps (dict[int, tuple[str, int]] | None) – An optional map for post-circuit check measurements.
  • measure_map_pre (dict[int, tuple[str, int]] | None) – An optional map for pre-circuit check measurements.
  • post_check_suffix (str) – The suffix of the post-circuit check registers.
  • pre_check_suffix (str) – The suffix of the pre-circuit check registers.
  • spectator_cregs (set[str] | None) – Names of primary registers that hold spectator measurements (the first half of the spectator parity check produced by AddSpectatorPostCircuitBitFlipChecks).

edges

Type: set[frozenset[int]]

A set of edges to consider for edge-based postselection.

from_circuit

classmethod from_circuit(circuit, coupling_map, *, post_check_suffix='_ps', pre_check_suffix='_pre', spectator_cregs=None)

GitHub

Initialize from quantum circuits.

Parameters

  • circuit (QuantumCircuit) – The circuit containing bit-flip checks..
  • coupling_map (CouplingMap |list[tuple[int, int]]) – A coupling map or a list of tuples indicating pairs of neighboring qubits.
  • post_check_suffix (str) – A fixed suffix for post-circuit check classical registers.
  • pre_check_suffix (str) – A fixed suffix for pre-circuit check classical registers.
  • spectator_cregs (set[str] | list[str] | None) – Names of primary registers that hold spectator measurements. Defaults to ["spec"], matching the default name used by AddSpectatorPostCircuitBitFlipChecks.

Return type

PostSelectionSummary

measure_map

Type: dict[int, tuple[str, int]]

A map from qubit indices to the register and clbit index used to measure those qubits.

measure_map_pre

Type: dict[int, tuple[str, int]]

A map from qubit indices to the register and clbit index for pre-circuit check measurements.

measure_map_ps

Type: dict[int, tuple[str, int]]

A map from qubit indices to the register and clbit index for post-circuit check measurements.

post_check_suffix

Type: str

The suffix of the post-circuit check registers.

pre_check_suffix

Type: str

The suffix of the pre-circuit check registers.

primary_cregs

Type: set[str]

The names of the primary classical registers.

spectator_cregs

Type: set[str]

Subset of primary_cregs that hold spectator measurements.

Use primary_cregs - spectator_cregs to get the data-only primary registers, e.g. when computing observables from filtered shots.

PostSelector

class PostSelector(summary)

GitHub

Bases: object

A class to process the results of bit-flip checks.

Initialize a PostSelector object.

Parameters

summary (PostSelectionSummary) – A summary of the circuit containing bit-flip checks.

compute_mask

compute_mask(result, strategy=PostSelectionStrategy.NODE, *, mode='post')

GitHub

Compute boolean masks indicating what shots should be kept or discarded.

By construction, the returned mask has the same shape as the arrays in the result, but with one fewer dimension (the last axis of every array, over clbits, is not present in the mask).

Parameters

  • result (dict[str, ndarray[tuple[int, ...], dtype[bool]]]) – The result to post-process. Must be a dictionary mapping register names to boolean arrays.
  • strategy (Literal['node', 'edge'] | ~qiskit_addon_utils.noise_management.bit_flip_checks.post_selector.PostSelectionStrategy) – The postselection strategy (“node” or “edge”).
  • mode (Literal['post', 'pre', 'both']) – Which type of postselection to apply: - “post”: Apply post-circuit checks only - “pre”: Apply pre-circuit checks only - “both”: Apply both pre and post-check

Returns

A boolean mask where True indicates shots to keep, False indicates shots to discard.

Raises

ValueError – If the requested mode is not available (e.g., no pre-check measurements in the circuit but mode=”pre” was requested).

Return type

ndarray[tuple[int, …], dtype[bool]]

from_circuit

classmethod from_circuit(circuit, coupling_map, *, post_check_suffix='_ps', pre_check_suffix='_pre', spectator_cregs=None)

GitHub

Initialize from a quantum circuit.

Parameters

  • circuit (QuantumCircuit) – The circuit containing bit-flip checks.
  • coupling_map (CouplingMap |list[tuple[int, int]]) – A coupling map or a list of tuples indicating pairs of neighboring qubits.
  • post_check_suffix (str) – A fixed suffix for classical registers associated with post-circuit checks.
  • pre_check_suffix (str) – A fixed suffix for classical registers associated with pre-circuit checks.
  • spectator_cregs (set[str] | list[str] | None) – Names of registers that hold spectator measurements (the first half of the spectator parity check produced by AddSpectatorPostCircuitBitFlipChecks). Defaults to ["spec"] to match AddSpectatorPostCircuitBitFlipChecks.

Return type

PostSelector

summary

Type: PostSelectionSummary

A summary of the circuit containing bit-flip checks.

PostSelectionStrategy

class PostSelectionStrategy(value)

GitHub

Bases: str, Enum

The supported postselection strategies.

EDGE

Default value: 'edge'

Discard every shot where there exists a pair of neighbouring qubits for which both checks fail.

NODE

Default value: 'node'

Discard every shot where one or more checks fail.

capitalize

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold

casefold()

Return a version of the string suitable for caseless comparisons.

center

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count

count(sub[, start[, end]]) → int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith

endswith(suffix[, start[, end]]) → bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find

find(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format

format(*args, **kwargs) → str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map

format_map(mapping) → str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index

index(sub[, start[, end]]) → int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower

lower()

Return a copy of the string converted to lowercase.

lstrip

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

maketrans

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind

rfind(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex

rindex(sub[, start[, end]]) → int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits (starting from the left). -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including \n \r \t \f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits (starting from the left). -1 (the default value) means no limit.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith

startswith(prefix[, start[, end]]) → bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper

upper()

Return a copy of the string converted to uppercase.

zfill

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

XSlowGate

class XSlowGate(label='xslow', xslow_gate_name='xslow')

GitHub

Bases: Gate

The x-slow gate.

Parameters

  • name – The name of the gate.
  • num_qubits – The number of qubits the gate acts on.
  • params – A list of parameters.
  • label (str) – An optional label for the gate.
  • xslow_gate_name (str)

add_decomposition

add_decomposition(decomposition)

Add a decomposition of the instruction to the SessionEquivalenceLibrary.

base_class

Type: type[Instruction]

Get the base class of this instruction. This is guaranteed to be in the inheritance tree of self.

The “base class” of an instruction is the lowest class in its inheritance tree that the object should be considered entirely compatible with for _all_ circuit applications. This typically means that the subclass is defined purely to offer some sort of programmer convenience over the base class, and the base class is the “true” class for a behavioral perspective. In particular, you should not override base_class if you are defining a custom version of an instruction that will be implemented differently by hardware, such as an alternative measurement strategy, or a version of a parametrized gate with a particular set of parameters for the purposes of distinguishing it in a Target from the full parametrized gate.

This is often exactly equivalent to type(obj), except in the case of singleton instances of standard-library instructions. These singleton instances are special subclasses of their base class, and this property will return that base. For example:

>>> isinstance(XGate(), XGate)
True
>>> type(XGate()) is XGate
False
>>> XGate().base_class is XGate
True

In general, you should not rely on the precise class of an instruction; within a given circuit, it is expected that Instruction.name should be a more suitable discriminator in most situations.

broadcast_arguments

broadcast_arguments(qargs, cargs)

Validation and handling of the arguments and its relationship.

For example, cx([q[0],q[1]], q[2]) means cx(q[0], q[2]); cx(q[1], q[2]). This method yields the arguments in the right grouping. In the given example:

in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
      [q[1], q[2]], []

The general broadcasting rules are:

  • If len(qargs) == 1:

    [q[0], q[1]] -> [q[0]],[q[1]]
  • If len(qargs) == 2:

    [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]
    [[q[0]], [r[0], r[1]]]       -> [q[0], r[0]], [q[0], r[1]]
    [[q[0], q[1]], [r[0]]]       -> [q[0], r[0]], [q[1], r[0]]
  • If len(qargs) >= 3:

    [q[0], q[1]], [r[0], r[1]],  ...] -> [q[0], r[0], ...], [q[1], r[1], ...]

Parameters

  • qargs (list) – List of quantum bit arguments.
  • cargs (list) – List of classical bit arguments.

Returns

A tuple with single arguments.

Raises

CircuitError – If the input is not valid. For example, the number of arguments does not match the gate expectation.

Return type

Iterable[tuple[list, list]]

control

control(num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=None)

Return the controlled version of itself.

The controlled gate is implemented as ControlledGate when annotated is False, and as AnnotatedOperation when annotated is True.

Deprecated since version 2.3

qiskit.circuit.gate.Gate.control()’s argument annotated is deprecated as of Qiskit 2.3. It will be removed in Qiskit 3.0. The method Gate.control() no longer accepts annotated=None. The new default is annotated=True, which represents the controlled gate as an AnnotatedOperation (unless a dedicated controlled-gate class already exists). You can explicitly set annotated=False to preserve the previous behavior. However, using annotated=True is recommended, as it defers construction of the controlled circuit to transpiler, and furthermore enables additional controlled-gate optimizations (typically leading to higher-quality circuits).

Parameters

  • num_ctrl_qubits (int) – Number of controls to add. Defaults to 1.
  • label (str | None) – Optional gate label. Defaults to None. Ignored if the controlled gate is implemented as an annotated operation.
  • ctrl_state (int |str | None) – The control state of the gate, specified either as an integer or a bitstring (e.g. "110"). If None, defaults to the all-ones state 2**num_ctrl_qubits - 1.
  • annotated (bool | None) – Indicates whether the controlled gate should be implemented as a controlled gate or as an annotated operation. If None, treated as False.

Returns

A controlled version of this gate.

Raises

QiskitError – invalid num_ctrl_qubits or ctrl_state.

copy

copy(name=None)

Copy of the instruction.

Parameters

name (str) – name to be given to the copied circuit, if None then the name stays the same.

Returns

a copy of the current instruction, with the name updated if it was provided

Return type

qiskit.circuit.Instruction

decompositions

Get the decompositions of the instruction from the SessionEquivalenceLibrary.

definition

Return definition in terms of other basic gates.

inverse

inverse(annotated=False)

Invert this instruction.

If annotated is False, the inverse instruction is implemented as a fresh instruction with the recursively inverted definition.

If annotated is True, the inverse instruction is implemented as AnnotatedOperation, and corresponds to the given instruction annotated with the “inverse modifier”.

Special instructions inheriting from Instruction can implement their own inverse (e.g. T and Tdg, Barrier, etc.) In particular, they can choose how to handle the argument annotated which may include ignoring it and always returning a concrete gate class if the inverse is defined as a standard gate.

Parameters

annotated (bool) – if set to True the output inverse gate will be returned as AnnotatedOperation.

Returns

The inverse operation.

Raises

CircuitError – if the instruction is not composite and an inverse has not been implemented for it.

is_parameterized

is_parameterized()

Return whether the Instruction contains compile-time parameters.

label

Type: str

Return instruction label

mutable

Type: bool

Is this instance is a mutable unique instance or not.

If this attribute is False the gate instance is a shared singleton and is not mutable.

name

Return the name.

num_clbits

Return the number of clbits.

num_qubits

Return the number of qubits.

params

The parameters of this Instruction. Ideally these will be gate angles.

power

power(exponent, annotated=False)

Raise this gate to the power of exponent.

Implemented either as a unitary gate (ref. UnitaryGate) or as an annotated operation (ref. AnnotatedOperation). In the case of several standard gates, such as RXGate, when the power of a gate can be expressed in terms of another standard gate that is returned directly.

Parameters

  • exponent (float) – the power to raise the gate to
  • annotated (bool) – indicates whether the power gate can be implemented as an annotated operation. In the case of several standard gates, such as RXGate, this argument is ignored when the power of a gate can be expressed in terms of another standard gate.

Returns

An operation implementing gate^exponent

Raises

CircuitError – If gate is not unitary

repeat

repeat(n)

Creates an instruction with self repeated nn times.

Parameters

n (int) – Number of times to repeat the instruction

Returns

Containing the definition.

Return type

qiskit.circuit.Instruction

Raises

CircuitError – If n < 1.

reverse_ops

reverse_ops()

For a composite instruction, reverse the order of sub-instructions.

This is done by recursively reversing all sub-instructions. It does not invert any gate.

Returns

a new instruction with

sub-instructions reversed.

Return type

qiskit.circuit.Instruction

soft_compare

soft_compare(other)

Soft comparison between gates. Their names, number of qubits, and classical bit numbers must match. The number of parameters must match. Each parameter is compared. If one is a ParameterExpression then it is not taken into account.

Parameters

other (instruction) – other instruction.

Returns

are self and other equal up to parameter expressions.

Return type

bool

to_matrix

to_matrix()

Return a Numpy.array for the gate unitary matrix.

Returns

if the Gate subclass has a matrix definition.

Return type

np.ndarray

Raises

CircuitError – If a Gate subclass does not implement this method an exception will be raised when this base class method is called.

to_mutable

to_mutable()

Return a mutable copy of this gate.

This method will return a new mutable copy of this gate instance. If a singleton instance is being used this will be a new unique instance that can be mutated. If the instance is already mutable it will be a deepcopy of that instance.

validate_parameter

validate_parameter(parameter)

Gate parameters should be int, float, or ParameterExpression

Was this page helpful?
Report a bug, typo, or request content on GitHub.