class Circuit
append
T,T_DAGon qubits, andTPP,TPP_DAGon Pauli products.R_X,R_Y,R_ZandU3on qubits,R_XX,R_YYandR_ZZon two distinct qubits, andR_PAULIon Pauli products.U3takes three angles(theta, phi, lambda)asarg, the others one. Angles are in units of π.CSandCS_DAGon bare qubit targets, in pairs, andCCZandCCXon bare qubit targets, in groups of three. They are appended as their Clifford+T decomposition.
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 astim.CircuitInstruction,stim.CircuitRepeatBlockorstim.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. Astim.GateTarget: Could be a variety of things. Methods likestim.target_rec,stim.target_sweep_bit,stim.target_x, andstim.CircuitInstruction.__getitem__all return this type. Astim.PauliString: This will automatically be expanded into a product of pauli targets likeX1*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
approx_equals
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.
bool— True if the given object is a circuit approximately equal up to thebool— receiving circuit up to the given tolerance, otherwise False.
compile_detector_sampler
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 explicitbatch_sizeand 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, onnumba.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”.
CompiledDetectorSampler— A CompiledDetectorSampler that can be used to sample detectors and observables.
ValueError— Ifdeviceis unknown, is not “auto” under a stabilizer-rank strategy, or is “metal” for a circuit that the GPU executor cannot run.RuntimeError— Ifdeviceis “metal” and this process cannot use an Apple GPU.
compile_m2d_converter
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).
stim.CompiledMeasurementsToDetectionEventsConverter— An initialized stim.CompiledMeasurementsToDetectionEventsConverter.
compile_sampler
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 explicitbatch_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, onnumba.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”.
CompiledMeasurementSampler— A CompiledMeasurementSampler that can be used to sample measurements.
ValueError— Ifdeviceis unknown, is not “auto” under a stabilizer-rank strategy, or is “metal” for a circuit that the GPU executor cannot run.RuntimeError— Ifdeviceis “metal” and this process cannot use an Apple GPU.
copy
detector_error_model
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 viastim.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 anyrepeatblocks. 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 asPAULI_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
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. Passingrange(A, B)for a detector slice will show the slices for ticks A through B including A but excluding B. Passingrange(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.
Any— An object whose__str__method returns the diagram, so thatAny— writing the diagram to a file works correctly. The returnedAny— object may also define methods such as_repr_html_, so thatAny— ipython notebooks recognize it can be shown using a specializedAny— viewer instead of as raw text.
flattened
from_file
filename(str) — The filename to read the circuit from.
Circuit— A new Circuit instance.
from_stim_program
stim_circuit(stim.Circuit) — The Stim circuit to wrap.
Circuit— A new Circuit instance.
get_graph
Circuit.to_tensor returns the
channel alone.
get_sampling_graph
- Wire starts become
|0⟩and wire ends are discarded. - Add outputs, which are classical boundaries:
(a) When sampling measurements (i.e.
sample_detectorsis 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_detectorsis True), add an output for each detector, then for each observable.
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.
Graph— A ZX graph for sampling.
inverse
pop
index(int) — Defaults to -1 (end of circuit). The index to pop from.
stim.CircuitInstruction | stim.CircuitRepeatBlock— The popped instruction or repeat block.
IndexError— The given index is outside the bounds of the circuit.
tcount
to_tensor
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
without_noise
class CompiledMeasurementSampler
stim.CompiledMeasurementSampler. Each measurement record of the
circuit is one output column.
sample
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. Withstrategy="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.
np.ndarray— A boolean array of shape(shots, num_measurements), or withnp.ndarray—bit_packeda uint8 array of shapenp.ndarray—(shots, ceil(num_measurements / 8))in little-endian bit order.
class CompiledDetectorSampler
sample
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. Withstrategy="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 lengthnum_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, withuse_detector_reference_sample) are returned, so the result can have fewer thanshotsrows, andlen(result) / shotsis the acceptance rate. Without a mask, exactlyshotsrows are returned. A shot that a masked direct detector (an error bit or a constant) discards skips the components; withstrategy="active_statevector"a masked component detector also stops a shot’s simulation, while stabilizer-rank components are computed in full.
np.ndarray | tuple[np.ndarray, np.ndarray]— A boolean array of shape(rows, num_columns), or withnp.ndarray | tuple[np.ndarray, np.ndarray]—bit_packeda uint8 array of shape(rows, ceil(num_columns / 8))np.ndarray | tuple[np.ndarray, np.ndarray]— in little-endian bit order.rowsisshots, or fewer with anp.ndarray | tuple[np.ndarray, np.ndarray]—postselection_mask. The columns are the detectors, with thenp.ndarray | tuple[np.ndarray, np.ndarray]— observables prepended and/or appended if requested. Withnp.ndarray | tuple[np.ndarray, np.ndarray]—separate_observables, a(detectors, observables)tuple of suchnp.ndarray | tuple[np.ndarray, np.ndarray]— arrays holding the same shots.
UserWarning— If a masked direct detector is a constant 1, withoutuse_detector_reference_sample, so that every shot is discarded.
ValueError— Ifseparate_observablesis combined withprepend_observablesorappend_observables.