tsim supports fast sampling from quantum circuits with few non-Clifford gates. It exposesDocumentation Index
Fetch the complete documentation index at: https://tsim.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
Circuit, CompiledDetectorSampler, and CompiledMeasurementSampler
objects, which follow the Stim API.
The package is organized as follows:
circuit.py: The thinCircuitwrapper aroundstim.Circuit.sampler.py: Orchestrates compilation and evaluation to sample measurements or detectors.core/: ZX graph construction, parsing, and data types.compile/: JAX compilation pipeline including stabilizer rank decomposition.noise/: Pauli noise channels and detector error models.utils/: Utility functions for visualization and linear algebra.
class Circuit
append
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.CircuitInstructionorstim.CircuitInstructionBlock, which results in the instruction or block being appended to the circuit. The other arguments (targets and arg) 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_sweet,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, and PAULI_CHANNEL_1 takes three disjoint probabilities.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.
cast_to_stim
stim.Circuit.
This is useful for passing the circuit to functions that expect a
stim.Circuit.
compile_detector_sampler
strategy(DecompositionStrategy) — Stabilizer rank decomposition strategy. Must be one of “cat5”, “bss”, “cutting”.seed(int | None) — Random seed for the sampler. IMPORTANT: Currently, the sampler will only produce deterministic samples for fixed batch size. If deterministic samples are needed, the batch size should be set manually.
CompiledDetectorSampler— A CompiledDetectorSampler that can be used to sample detectors and observables.
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(DecompositionStrategy) — Stabilizer rank decomposition strategy. Must be one of “cat5”, “bss”, “cutting”.seed(int | None) — Random seed for the sampler. IMPORTANT: Currently, the sampler will only produce deterministic samples for fixed batch size. If deterministic samples are needed, the batch size should be set manually.
CompiledMeasurementSampler— A CompiledMeasurementSampler that can be used to sample measurements.
copy
detector_error_model
allow_gauge_detectors is set to true.
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. This is not supported by tsim and setting it to true will raise an error. The argument is present for compatibility with stim.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) — 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, aPAULI_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['pyzx', 'pyzx-dets', 'pyzx-meas', 'timeline-svg', 'timeslice-svg']) — The type of diagram. Available types are: “pyzx”: A pyzx SVG of the ZX diagram of the circuit. “pyzx-dets”: A pyzx SVG of the ZX diagram that is used to compute probabilities of detectors and observables. “pyzx-meas”: A pyzx SVG of the ZX diagram 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.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
get_sampling_graph
- Double the ZX-diagram by composing it with its adjoint.
- Connect all rec[i] vertices to their corresponding adjoint rec[i] vertices.
- Add outputs:
(a) When sampling measurements (i.e.
sample_detectorsis False), add output nodes 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 output nodes for each detector and observable. Only one set of detector and observable nodes is kept, i.e., detectors and observables are not composed with their adjoints.
sample_detectors(bool) — If True, sample detectors and observables instead of measurements.
BaseGraph— 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_matrix
to_tensor
without_annotations
without_noise
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 in each batch. Defaults to None, which automatically chooses a batch size based on available memory. When using a GPU, setting this explicitly can help fully utilize VRAM for maximum performance. NOTE: Changing the batch size will affect reproducibility even with a fixed 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.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.
np.ndarray | tuple[np.ndarray, np.ndarray]— A numpy array or tuple of numpy arrays containing the samples.
ValueError— Ifseparate_observablesis combined withprepend_observablesorappend_observables.
class CompiledMeasurementSampler
- compiled_scalar_graphs[0]: normalization (0 outputs plugged)
- compiled_scalar_graphs[i]: cumulative probability up to bit i
sample
shots(int) — The number of times to sample every measurement in the circuit.batch_size(int | None) — The number of samples to process in each batch. Defaults to None, which automatically chooses a batch size based on available memory. When using a GPU, setting this explicitly can help fully utilize VRAM for maximum performance. NOTE: Changing the batch size will affect reproducibility even with a fixed seed.
np.ndarray— A numpy array containing the measurement samples.