Skip to main content

class Circuit

Quantum circuit as a thin wrapper around stim.Circuit. Circuits are constructed like Stim circuits: >>> circuit = Circuit(''' … H 0 … T 0 … CNOT 0 1 … M 0 1 … ''')

append

Append an operation into the circuit. Besides Stim’s gates, this accepts Tsim’s gates:
  • T, T_DAG on qubits, and TPP, TPP_DAG on Pauli products.
  • R_X, R_Y, R_Z and U3 on qubits, R_XX, R_YY and R_ZZ on two distinct qubits, and R_PAULI on Pauli products. U3 takes three angles (theta, phi, lambda) as arg, the others one. Angles are in units of π.
  • CS and CS_DAG on bare qubit targets, in pairs, and CCZ and CCX on bare qubit targets, in groups of three. They are appended as their Clifford+T decomposition.
The other Tsim gates are stored as tagged Clifford placeholders. Gate names are case-insensitive. Parameters:
  • name (str | stim.CircuitInstruction | stim.CircuitRepeatBlock | stim.Circuit) — The name of the operation’s gate (e.g. “H” or “M” or “CNOT”). This argument can also be set to a stim.CircuitInstruction, stim.CircuitRepeatBlock or stim.Circuit, which results in the instruction, block or circuit being appended to the circuit. The other arguments (targets, arg and tag) can’t be specified when doing so.
  • targets (int | stim.GateTarget | stim.PauliString | Iterable[int | stim.GateTarget | stim.PauliString]) — The objects operated on by the gate. This can be either a single target or an iterable of multiple targets. Each target can be: An int: The index of a targeted qubit. A stim.GateTarget: Could be a variety of things. Methods like stim.target_rec, stim.target_sweep_bit, stim.target_x, and stim.CircuitInstruction.__getitem__ all return this type. A stim.PauliString: This will automatically be expanded into a product of pauli targets like X1*Y2*Z3.
  • arg (float | Iterable[float] | None) — The “parens arguments” for the gate, such as the probability for a noise operation. A double or list of doubles parameterizing the gate. Different gates take different parens arguments. For example, X_ERROR takes a probability, OBSERVABLE_INCLUDE takes an observable index, PAULI_CHANNEL_1 takes three disjoint probabilities, and R_X takes an angle in units of π.
  • tag (str) — A customizable string attached to the instruction.

append_from_stim_program_text

Append operations described by a Stim format program into the circuit. Supports the same shorthand syntax as the constructor.

approx_equals

Check if a circuit is approximately equal to another circuit. Two circuits are approximately equal if they are equal up to slight perturbations of instruction arguments such as probabilities. For example, X_ERROR(0.100) 0 is approximately equal to X_ERROR(0.099) within an absolute tolerance of 0.002. All other details of the circuits (such as the ordering of instructions and targets) must be exactly the same. Parameters:
  • other (object) — The circuit, or other object, to compare to this one.
  • atol (float) — The absolute error tolerance. The maximum amount each probability may have been perturbed by.
Returns:
  • bool — True if the given object is a circuit approximately equal up to the
  • bool — receiving circuit up to the given tolerance, otherwise False.

compile_detector_sampler

Compile circuit into a detector sampler. Connected components whose single output is deterministically given by one f-variable, or is a constant, are handled via a fast direct path (no compilation or autoregressive sampling). Remaining components go through the full compilation pipeline. Parameters:
  • strategy (SamplingStrategy) — “active_statevector” (the default) to simulate each non-direct component on a dense state vector over its active qubits, or a stabilizer rank decomposition strategy (“cat5”, “bss”, “cutting”). The stabilizer rank strategies are provisional.
  • seed (int | None) — Random seed for the sampler. If None, a random seed is drawn. A seed reproduces its samples only with the same versions of Tsim and its dependencies (such as NumPy and JAX) and the same backend (CPU or GPU). With “active_statevector”, and under any strategy for a circuit without non-direct components, the samples of a seed depend on neither the batch size nor the thread count. With a stabilizer-rank strategy they also need the same explicit batch_size and the same reference sample settings, since the default batch size depends on the free memory. On a GPU, they do depend on the batch size.
  • device (Device) — Where “active_statevector” samples. “auto” (the default) samples in float32 on an Apple GPU when there is one that can run the circuit, and otherwise on the CPU, without a warning. “cpu” samples on the CPU in float64, on numba.get_num_threads() threads. “metal” samples on an Apple GPU or raises: without one, for a component of more than 11 active qubits, a rotation within about 6e-5 π of a multiple of π/2, noise beyond the GPU’s tables, or a call that runs out of GPU memory. The stabilizer rank strategies take only “auto”.
Returns:
  • CompiledDetectorSampler — A CompiledDetectorSampler that can be used to sample detectors and observables.
Raises:
  • ValueError — If device is unknown, is not “auto” under a stabilizer-rank strategy, or is “metal” for a circuit that the GPU executor cannot run.
  • RuntimeError — If device is “metal” and this process cannot use an Apple GPU.

compile_m2d_converter

Create a measurement-to-detection-event converter for the given circuit. The converter can efficiently compute detection events and observable flips from raw measurement data. The converter uses a noiseless reference sample, collected from the circuit using Stim’s Tableau simulator during initialization of the converter, as a baseline for determining what the expected value of a detector is. Note that the expected behavior of gauge detectors (detectors that are not actually deterministic under noiseless execution) can vary depending on the reference sample. Stim mitigates this by always generating the same reference sample for a given circuit. Parameters:
  • skip_reference_sample (bool) — Defaults to False. When set to True, the reference sample used by the converter is initialized to all-zeroes instead of being collected from the circuit. This should only be used if it’s known that the all-zeroes sample is actually a possible result from the circuit (under noiseless execution).
Returns:
  • stim.CompiledMeasurementsToDetectionEventsConverter — An initialized stim.CompiledMeasurementsToDetectionEventsConverter.

compile_sampler

Compile circuit into a measurement sampler. Parameters:
  • strategy (SamplingStrategy) — “active_statevector” (the default) to simulate each non-direct component on a dense state vector over its active qubits, or a stabilizer rank decomposition strategy (“cat5”, “bss”, “cutting”). The stabilizer rank strategies are provisional.
  • seed (int | None) — Random seed for the sampler. If None, a random seed is drawn. A seed reproduces its samples only with the same versions of Tsim and its dependencies (such as NumPy and JAX) and the same backend (CPU or GPU). With “active_statevector”, and under any strategy for a circuit without non-direct components, the samples of a seed depend on neither the batch size nor the thread count. With a stabilizer-rank strategy they also need the same explicit batch_size, since the default batch size depends on the free memory. On a GPU, they do depend on the batch size.
  • device (Device) — Where “active_statevector” samples. “auto” (the default) samples in float32 on an Apple GPU when there is one that can run the circuit, and otherwise on the CPU, without a warning. “cpu” samples on the CPU in float64, on numba.get_num_threads() threads. “metal” samples on an Apple GPU or raises: without one, for a component of more than 11 active qubits, a rotation within about 6e-5 π of a multiple of π/2, noise beyond the GPU’s tables, or a call that runs out of GPU memory. The stabilizer rank strategies take only “auto”.
Returns:
  • CompiledMeasurementSampler — A CompiledMeasurementSampler that can be used to sample measurements.
Raises:
  • ValueError — If device is unknown, is not “auto” under a stabilizer-rank strategy, or is “metal” for a circuit that the GPU executor cannot run.
  • RuntimeError — If device is “metal” and this process cannot use an Apple GPU.

copy

Create a copy of this circuit.

detector_error_model

Return a stim.DetectorErrorModel describing the error processes in the circuit. Unlike the stim.Circuit.detector_error_model() method, this method allows for non-deterministic observables when allow_gauge_detectors is set to true. Warning: By default (decompose_errors=False) the model is not decomposed. Matching decoders such as PyMatching build their graph only from error mechanisms that flip at most two detectors, and silently ignore the rest, which can raise the logical error rate substantially. Set decompose_errors=True when the model is meant for a matching decoder. Parameters:
  • decompose_errors (bool) — Defaults to false. When set to true, the error analysis attempts to decompose the components of composite error mechanisms (such as depolarization errors) into simpler errors, and suggest this decomposition via stim.target_separator() between the components. For example, in an XZ surface code, single qubit depolarization has a Y error term which can be decomposed into simpler X and Z error terms. Decomposition fails (causing this method to throw) if it’s not possible to decompose large errors into simple errors that affect at most two detectors. Decomposition keeps the logical observables as observables, as Stim does, so it requires them to be deterministic: Stim raises a ValueError otherwise.
  • flatten_loops (bool) — Defaults to false. When set to true, the output will not contain any repeat blocks. When set to false, the error analysis watches for loops in the circuit reaching a periodic steady state with respect to the detectors being introduced, the error mechanisms that affect them, and the locations of the logical observables. When it identifies such a steady state, it outputs a repeat block. This is massively more efficient than flattening for circuits that contain loops, but creates a more complex output. Irrelevant unless allow_gauge_detectors=False.
  • allow_gauge_detectors (bool) — Defaults to false. When set to false, the error analysis verifies that detectors in the circuit are actually deterministic under noiseless execution of the circuit. Note that, unlike in Stim, logical observables are also allowed to be non-deterministic.
  • approximate_disjoint_errors (bool | float) — Defaults to false. When set to false, composite error mechanisms with disjoint components (such as PAULI_CHANNEL_1(0.1, 0.2, 0.0)) can cause the error analysis to throw exceptions (because detector error models can only contain independent error mechanisms). When set to true, the probabilities of the disjoint cases are instead assumed to be independent probabilities. For example, a “PAULI_CHANNEL_1(0.1, 0.2, 0.0)becomes equivalent to anX_ERROR(0.1)followed by aZ_ERROR(0.2)`. This assumption is an approximation, but it is a good approximation for small probabilities. This argument can also be set to a probability between 0 and 1, setting a threshold below which the approximation is acceptable. Any error mechanisms that have a component probability above the threshold will cause an exception to be thrown.
  • ignore_decomposition_failures (bool) — Defaults to False. When this is set to True, circuit errors that fail to decompose into graphlike detector error model errors no longer cause the conversion process to abort. Instead, the undecomposed error is inserted into the output. Whatever tool the detector error model is then given to is responsible for dealing with the undecomposed errors (e.g. a tool may choose to simply ignore them). Irrelevant unless decompose_errors=True.
  • block_decomposition_from_introducing_remnant_edges (bool) — Defaults to False. Requires that both A B and C D be present elsewhere in the detector error model in order to decompose A B C D into A B ^ C D. Normally, only one of A B or C D needs to appear to allow this decomposition. Remnant edges can be a useful feature for ensuring decomposition succeeds, but they can also reduce the effective code distance by giving the decoder single edges that actually represent multiple errors in the circuit (resulting in the decoder making misinformed choices when decoding). Irrelevant unless decompose_errors=True.

diagram

Return a diagram of the circuit, from a variety of options. Parameters:
  • type (Literal['zx', 'zx-dets', 'zx-meas', 'timeline-svg', 'timeslice-svg', 'timeline-text']) — The type of diagram. Available types are: “zx”: A zxparam D3 drawing of the circuit’s quantum/classical ZX graph. “zx-dets”: A zxparam D3 drawing of the reduced ZX graph that is used to compute probabilities of detectors and observables. “zx-meas”: A zxparam D3 drawing of the reduced ZX graph that is used to compute probabilities of measurements. “timeline-svg”: An SVG image of the operations applied by the circuit over time. Includes annotations showing the measurement record index that each measurement writes to, and the measurements used by detectors. “timeslice-svg”: An SVG image of the operations applied between two TICK instructions in the circuit, with the operations laid out in 2d. “timeline-text”: An ASCII text diagram of the operations applied by the circuit over time, with Tsim’s custom gates rendered under their logical names rather than the Clifford placeholders used to store them.
  • tick (int | range | None) — Required for time slice diagrams. Specifies which TICK instruction, or range of TICK instructions, to slice at. Note that the first TICK instruction in the circuit corresponds tick=1. The value tick=0 refers to the very start of the circuit. Passing range(A, B) for a detector slice will show the slices for ticks A through B including A but excluding B. Passing range(A, B) for a time slice will show the operations between tick A and tick B.
  • rows (int | None) — In diagrams that have multiple separate pieces, such as timeslice diagrams and detslice diagrams, this controls how many rows of pieces there will be. If not specified, a number of rows that creates a roughly square layout will be chosen.
  • filter_coords (Iterable[Iterable[float] | stim.DemTarget]) — A list of things to include in the diagram. Different effects depending on the diagram. For detslice diagrams, the filter defaults to showing all detectors and no observables. When specified, each list entry can be a collection of floats (detectors whose coordinates start with the same numbers will be included), a stim.DemTarget (specifying a detector or observable to include), a string like “D5” or “L0” specifying a detector or observable to include.
  • height (float | None) — Optional height for the rendered diagram in pixels. Only applied to timeline-svg and timeslice-svg diagram types. For timeline-svg, when both height and width are None, the height is automatically determined based on the number of qubits. When only one dimension is given, the other is computed from the SVG aspect ratio.
  • width (float | None) — Optional width for the rendered diagram in pixels. Only applied to timeline-svg and timeslice-svg diagram types.
  • zoomable (bool) — If True (default), wraps SVG diagrams in an interactive container with pan and Ctrl/Cmd+wheel zoom. Only applies to timeline-svg and timeslice-svg diagram types.
  • **kwargs (Any) — Additional keyword arguments passed to the underlying diagram renderer.
Returns:
  • Any — An object whose __str__ method returns the diagram, so that
  • Any — writing the diagram to a file works correctly. The returned
  • Any — object may also define methods such as _repr_html_, so that
  • Any — ipython notebooks recognize it can be shown using a specialized
  • Any — viewer instead of as raw text.

flattened

Return a copy of the circuit with all repeat blocks expanded.

from_file

Create a Circuit from a file. Parameters:
  • filename (str) — The filename to read the circuit from.
Returns:
  • Circuit — A new Circuit instance.

from_stim_program

Create a Circuit from a stim.Circuit object. Parameters:
  • stim_circuit (stim.Circuit) — The Stim circuit to wrap.
Returns:
  • Circuit — A new Circuit instance.

get_graph

Construct the circuit’s quantum/classical ZX graph, with qubit ports. Error parameters have the error index as their ID. Each detector and observable is a classical XOR spider with its own classical output boundary; their ports follow the qubit outputs (detectors, then observables), so the graph’s tensor is the circuit’s channel together with the detector and observable bits. Circuit.to_tensor returns the channel alone.

get_sampling_graph

Get a ZX graph that can be used to compute probabilities. The graph is not doubled: qubit wires are quantum and measurement records are classical spiders. It is constructed as follows:
  1. Wire starts become |0⟩ and wire ends are discarded.
  2. Add outputs, which are classical boundaries: (a) When sampling measurements (i.e. sample_detectors is False), add an output for each measurement. Detectors and observables are removed since they are ignored when sampling measurements. (b) When sampling detectors and observables (i.e. sample_detectors is True), add an output for each detector, then for each observable.
Error parameters have the error index as their ID, so the graph’s to_tensor needs a bit for every error index in its bindings (unbound parameters raise); its tensor is then the joint distribution of the outputs. Parameters:
  • sample_detectors (bool) — If True, sample detectors and observables instead of measurements.
Returns:
  • Graph — A ZX graph for sampling.

inverse

Return the inverse of the circuit.

pop

Pops an operation from the end of the circuit, or at the given index. Parameters:
  • index (int) — Defaults to -1 (end of circuit). The index to pop from.
Returns:
  • stim.CircuitInstruction | stim.CircuitRepeatBlock — The popped instruction or repeat block.
Raises:
  • IndexError — The given index is outside the bounds of the circuit.

tcount

Count the spiders whose angle is not a multiple of π/2.

to_tensor

Return the circuit’s doubled tensor (its channel, U ⊗ Ū for unitaries). Axes follow zxparam’s Graph.to_tensor: outputs then inputs, by qubit, each with a copy and a conjugate axis. Only qubits that some instruction targets get axes, in increasing index order; qubits that no instruction names are left out, so H 1 gives a one-qubit tensor (add I q to keep qubit q). Error bits default to 0 (the noiseless circuit); bindings maps error indices to bits and raises ValueError for any other key. Detector and observable annotations are left out. Needs zxparam[quimb].

without_annotations

Return a copy of the circuit with all detector and observable annotations removed.

without_noise

Return a copy of the circuit with all noise removed.

class CompiledMeasurementSampler

Samples measurement outcomes from a quantum circuit. Follows stim.CompiledMeasurementSampler. Each measurement record of the circuit is one output column.

sample

Sample measurement outcomes from the circuit. Parameters:
  • shots (int) — The number of times to sample every measurement in the circuit.
  • batch_size (int | None) — The number of samples to process at once. Defaults to None, which chooses it from the available memory. With strategy="active_statevector" it bounds the shots a thread holds and does not change the samples. With a stabilizer-rank strategy on a GPU, setting this explicitly can help fully utilize VRAM; it changes the samples of a seed.
  • bit_packed (bool) — Defaults to false. When set, results are bit-packed. The packed rows may be a strided view of a wider array.
Returns:
  • np.ndarray — A boolean array of shape (shots, num_measurements), or with
  • np.ndarray — bit_packed a uint8 array of shape
  • np.ndarray — (shots, ceil(num_measurements / 8)) in little-endian bit order.

class CompiledDetectorSampler

Samples detector and observable outcomes from a quantum circuit.

sample

Return detector samples from the circuit. The circuit must define the detectors using DETECTOR instructions. Observables defined by OBSERVABLE_INCLUDE instructions can also be included in the results as honorary detectors. Parameters:
  • shots (int) — The number of times to sample every detector in the circuit.
  • batch_size (int | None) — The number of samples to process at once. Defaults to None, which chooses it from the available memory. With strategy="active_statevector" it bounds the shots a thread holds and does not change the samples. With a stabilizer-rank strategy on a GPU, setting this explicitly can help fully utilize VRAM; it changes the samples of a seed.
  • separate_observables (bool) — Defaults to False. When set to True, the return value is a (detection_events, observable_flips) tuple instead of a flat detection_events array.
  • prepend_observables (bool) — Defaults to false. When set, observables are included with the detectors and are placed at the start of the results.
  • append_observables (bool) — Defaults to false. When set, observables are included with the detectors and are placed at the end of the results.
  • bit_packed (bool) — Defaults to false. When set, results are bit-packed. The packed rows may be a strided view of a wider array.
  • use_detector_reference_sample (bool) — Defaults to False. When True, a noiseless reference sample is computed and XORed with detector outcomes so that results represent deviations from the noiseless baseline. This should only be used when detectors are deterministic. Otherwise, it can unpredictably change the results.
  • use_observable_reference_sample (bool) — Defaults to False. When True, a noiseless reference sample is computed and XORed with observable outcomes so that results represent deviations from the noiseless baseline. This should only be used when observables are deterministic. Otherwise, it can unpredictably change the results.
  • postselection_mask (np.ndarray | None) — Optional boolean array of length num_detectors. When set, only the shots in which every masked detector reads 0 in the returned sample (after the reference sample is XOR-ed in, with use_detector_reference_sample) are returned, so the result can have fewer than shots rows, and len(result) / shots is the acceptance rate. Without a mask, exactly shots rows are returned. A shot that a masked direct detector (an error bit or a constant) discards skips the components; with strategy="active_statevector" a masked component detector also stops a shot’s simulation, while stabilizer-rank components are computed in full.
Returns:
  • np.ndarray | tuple[np.ndarray, np.ndarray] — A boolean array of shape (rows, num_columns), or with
  • np.ndarray | tuple[np.ndarray, np.ndarray] — bit_packed a uint8 array of shape (rows, ceil(num_columns / 8))
  • np.ndarray | tuple[np.ndarray, np.ndarray] — in little-endian bit order. rows is shots, or fewer with a
  • np.ndarray | tuple[np.ndarray, np.ndarray] — postselection_mask. The columns are the detectors, with the
  • np.ndarray | tuple[np.ndarray, np.ndarray] — observables prepended and/or appended if requested. With
  • np.ndarray | tuple[np.ndarray, np.ndarray] — separate_observables, a (detectors, observables) tuple of such
  • np.ndarray | tuple[np.ndarray, np.ndarray] — arrays holding the same shots.
Warns:
  • UserWarning — If a masked direct detector is a constant 1, without use_detector_reference_sample, so that every shot is discarded.
Raises:
  • ValueError — If separate_observables is combined with prepend_observables or append_observables.