> ## Documentation Index
> Fetch the complete documentation index at: https://tsim.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# graph

> ZX graph construction, manipulation, and preparation for sampling.

## class `Circuit`

```python theme={null}
Circuit(stim_program_text: str = '')
```

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`

```python theme={null}
append(name: str | stim.CircuitInstruction | stim.CircuitRepeatBlock | stim.Circuit, targets: int | stim.GateTarget | stim.PauliString | Iterable[int | stim.GateTarget | stim.PauliString] = (), arg: float | Iterable[float] | None = None, tag: str = '') -> None
```

Append an operation into the circuit.

**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` or `stim.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. A `stim.GateTarget`: Could be a variety of things. Methods like `stim.target_rec`, `stim.target_sweet`, `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, and PAULI\_CHANNEL\_1 takes three disjoint probabilities.
* `tag` (`str`) — A customizable string attached to the instruction.

### `append_from_stim_program_text`

```python theme={null}
append_from_stim_program_text(stim_program_text: str) -> None
```

Append operations described by a Stim format program into the circuit.

Supports the same shorthand syntax as the constructor.

### `approx_equals`

```python theme={null}
approx_equals(other: object, atol: float) -> bool
```

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.

### `cast_to_stim`

```python theme={null}
cast_to_stim() -> stim.Circuit
```

Return self with type cast to `stim.Circuit`.

This is useful for passing the circuit to functions that expect a
`stim.Circuit`.

### `compile_detector_sampler`

```python theme={null}
compile_detector_sampler(strategy: DecompositionStrategy = 'cat5', seed: int | None = None) -> CompiledDetectorSampler
```

Compile circuit into a detector sampler.

Connected components whose single output is deterministically given by
one f-variable are handled via a fast direct path (no compilation or
autoregressive sampling).  Remaining components go through the full
compilation pipeline.

**Parameters:**

* `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.

**Returns:**

* `CompiledDetectorSampler` — A CompiledDetectorSampler that can be used to sample detectors and observables.

### `compile_m2d_converter`

```python theme={null}
compile_m2d_converter(skip_reference_sample: bool = False) -> stim.CompiledMeasurementsToDetectionEventsConverter
```

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`

```python theme={null}
compile_sampler(strategy: DecompositionStrategy = 'cat5', seed: int | None = None) -> CompiledMeasurementSampler
```

Compile circuit into a measurement sampler.

**Parameters:**

* `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.

**Returns:**

* `CompiledMeasurementSampler` — A CompiledMeasurementSampler that can be used to sample measurements.

### `copy`

```python theme={null}
copy() -> Circuit
```

Create a copy of this circuit.

### `detector_error_model`

```python theme={null}
detector_error_model(decompose_errors: bool = False, flatten_loops: bool = False, allow_gauge_detectors: bool = False, approximate_disjoint_errors: bool = False, ignore_decomposition_failures: bool = False, block_decomposition_from_introducing_remnant_edges: bool = False) -> stim.DetectorErrorModel
```

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.

**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. 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 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`) — 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 an `X_ERROR(0.1)` followed by a `Z_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`

```python theme={null}
diagram(type: Literal['pyzx', 'pyzx-dets', 'pyzx-meas', 'timeline-svg', 'timeslice-svg'] = 'timeline-svg', tick: int | range | None = None, filter_coords: Iterable[Iterable[float] | stim.DemTarget] = ((),), rows: int | None = None, height: float | None = None, width: float | None = None, zoomable: bool = True, kwargs: Any = {}) -> Any
```

Return a diagram of the circuit, from a variety of options.

**Parameters:**

* `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. 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`

```python theme={null}
flattened() -> Circuit
```

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

### `from_file`

```python theme={null}
from_file(cls, filename: str) -> Circuit
```

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`

```python theme={null}
from_stim_program(cls, stim_circuit: stim.Circuit) -> Circuit
```

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`

```python theme={null}
get_graph() -> BaseGraph
```

Construct the ZX graph.

### `get_sampling_graph`

```python theme={null}
get_sampling_graph(sample_detectors: bool = False) -> BaseGraph
```

Get a ZX graph that can be used to compute probabilities.

This graph will be constructed as follows:

1. Double the ZX-diagram by composing it with its adjoint.
2. Connect all rec\[i] vertices to their corresponding adjoint rec\[i] vertices.
3. Add outputs:
   (a) When sampling measurements (i.e. `sample_detectors` is 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_detectors` is 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.

**Parameters:**

* `sample_detectors` (`bool`) — If True, sample detectors and observables instead of measurements.

**Returns:**

* `BaseGraph` — A ZX graph for sampling.

### `inverse`

```python theme={null}
inverse() -> Circuit
```

Return the inverse of the circuit.

### `pop`

```python theme={null}
pop(index: int = -1) -> stim.CircuitInstruction | stim.CircuitRepeatBlock
```

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`

```python theme={null}
tcount() -> int
```

Count the number of T gates in the circuit.

### `to_matrix`

```python theme={null}
to_matrix() -> Any
```

Convert circuit to matrix representation.

### `to_tensor`

```python theme={null}
to_tensor() -> Any
```

Convert circuit to tensor representation.

### `without_annotations`

```python theme={null}
without_annotations() -> Circuit
```

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

### `without_noise`

```python theme={null}
without_noise() -> Circuit
```

Return a copy of the circuit with all noise removed.

## class `ConnectedComponent`

```python theme={null}
ConnectedComponent(graph: BaseGraph, output_indices: list[int])
```

A connected subgraph with its associated output indices.

## class `GraphRepresentation`

```python theme={null}
GraphRepresentation(graph: GraphS = GraphS(), rec: list[int] = list(), silent_rec: list[int] = list(), detectors: list[int] = list(), observables_dict: dict[int, int] = dict(), first_vertex: dict[int, int] = dict(), last_vertex: dict[int, int] = dict(), channel_probs: list[np.ndarray] = list(), correlated_error_probs: list[float] = list(), num_error_bits: int = 0, num_correlated_error_bits: int = 0, track_classical_wires: bool = False)
```

ZX graph built from a stim circuit.

Contains the graph and all auxiliary data needed for sampling.

## class `SamplingGraph`

```python theme={null}
SamplingGraph(graph: BaseGraph, error_transform: np.ndarray, channel_probs: list[np.ndarray], num_outputs: int, num_detectors: int)
```

Result of the graph preparation phase for sampling.

Contains all data structures needed for sampling. This represents a circuit
that has been:

1. Parsed from stim format
2. Converted to a ZX graph
3. Doubled (composed with adjoint)
4. Reduced via zx.full\_reduce
5. Had its error basis transformed (Gaussian elimination: e → f)

## `build_sampling_graph`

```python theme={null}
build_sampling_graph(built: GraphRepresentation, sample_detectors: bool = False) -> BaseGraph
```

Build a ZX graph for sampling from a GraphRepresentation.

This is the internal implementation of get\_sampling\_graph.

## `classify_direct`

```python theme={null}
classify_direct(component: ConnectedComponent) -> tuple[int, bool] | None
```

Check if a component is directly determined by a single f-variable.

A component qualifies when its graph consists of exactly two vertices — one
boundary output and one Z-spider — connected by a Hadamard edge, where the
Z-spider carries a single `f` parameter and a constant phase of either 0
(no flip) or π (flip).

**Parameters:**

* `component` (`ConnectedComponent`) — A connected component to classify.

**Returns:**

* `tuple[int, bool] | None` — `(f_index, flip)` if the fast path applies, otherwise `None`.

## `connected_components`

```python theme={null}
connected_components(g: BaseGraph) -> list[ConnectedComponent]
```

Return each connected component of `g` as its own ZX subgraph.

Each component is packaged inside a :class:`ConnectedComponent` that contains
the subgraph and a list of output indices matching the original output indices.

## `evaluate_graph`

```python theme={null}
evaluate_graph(g: GraphS, vals: dict[str, Fraction] | None = None) -> np.ndarray
```

Evaluate a ZX graph to a tensor with given parameter values.

## `find_basis`

```python theme={null}
find_basis(vectors: np.ndarray) -> tuple[np.ndarray, np.ndarray]
```

Decompose a set of binary vectors into a basis subset and a transformation matrix over GF(2).

Given a set of vectors V, this function finds a maximal linearly independent subset B
(the basis) and computes a transformation matrix T such that the original vectors can be
reconstructed from the basis via matrix multiplication over GF(2):

V = T @ B (mod 2)

**Parameters:**

* `vectors` (`np.ndarray`) — Input binary vectors of shape `(N, D)`. Can be a list of lists or a numpy array. Elements should be 0 or 1 (or convertible to them).

**Returns:**

* `tuple[np.ndarray, np.ndarray]` — A tuple `(basis, transform)` where: basis: The subset of independent vectors, shape `(K, D)`, where `K` is the rank. transform: The transformation matrix, shape `(N, K)`.

## `get_params`

```python theme={null}
get_params(g: BaseGraph) -> set[str]
```

Get all parameter variables that appear in the graph and its scalar.

Collects variables from:

* Vertex phases (g.\_phaseVars)
* Scalar phase variables (phasevars\_pi, phasevars\_pi\_pair, phasevars\_halfpi)
* Scalar phase pairs (phasepairs with paramsA, paramsB)
* Scalar phase nodes (phasenodevars)

**Parameters:**

* `g` (`BaseGraph`) — A ZX graph with parametrized phases

**Returns:**

* `set[str]` — Set of all variable names (e.g., \{'f0', 'f2', 'm1'}) that appear in the graph

## `parse_stim_circuit`

```python theme={null}
parse_stim_circuit(stim_circuit: stim.Circuit, track_classical_wires: bool = False) -> GraphRepresentation
```

Parse a stim circuit into a GraphRepresentation.

**Parameters:**

* `stim_circuit` (`stim.Circuit`) — The stim circuit to convert.
* `track_classical_wires` (`bool`) — Whether to track classical wires.

**Returns:**

* `GraphRepresentation` — A GraphRepresentation containing the ZX graph and all auxiliary data.

## `prepare_graph`

```python theme={null}
prepare_graph(circuit: Circuit, sample_detectors: bool) -> SamplingGraph
```

Prepare a circuit for compilation.

This function performs the graph preparation phase:

1. Parse the stim circuit into a ZX graph
2. Build the sampling graph (compose with adjoint, add outputs)
3. Reduce the graph via zx.full\_reduce
4. Transform error basis via Gaussian elimination (e → f)
5. Clear the scalar (safe before stabilizer rank decomposition)

**Parameters:**

* `circuit` (`Circuit`) — The quantum circuit to prepare.
* `sample_detectors` (`bool`) — If True, prepare for detector sampling. If False, prepare for measurement sampling.

**Returns:**

* `SamplingGraph` — A SamplingGraph containing the reduced graph and error transformation.

## `scale_horizontally`

```python theme={null}
scale_horizontally(g: BaseGraph, scale: float) -> None
```

Scale horizontal positions of graph vertices by a factor of `scale`.

**Parameters:**

* `g` (`BaseGraph`) — A ZX graph
* `scale` (`float`) — The factor to scale the graph by

## `squash_graph`

```python theme={null}
squash_graph(g: BaseGraph) -> None
```

Compact the graph by placing vertices underneath their output connections.

Starting from output vertices, each vertex is placed directly underneath
(same row, qubit - 1) its already-placed neighbor. Positions are assigned
via BFS traversal from outputs, ensuring no (qubit, row) collisions.

## `transform_error_basis`

```python theme={null}
transform_error_basis(g: BaseGraph, num_e: int | None = None) -> tuple[BaseGraph, np.ndarray]
```

Transform phase variables from the original 'e' basis to a reduced 'f' basis.

This function finds a linearly independent basis for the phase variables
across all vertices and transforms them accordingly. The original variables
(e0, e1, ...) are mapped to a smaller set (f0, f1, ...) where each f\_i
corresponds to a linear combination of original e variables.

**Parameters:**

* `g` (`BaseGraph`) — A ZX graph with phase variables attached to vertices.
* `num_e` (`int | None`) — Total number of e-variables. If provided, the returned matrix will have exactly this many columns (padded with zeros if needed). If None, the matrix will have only the columns that appear in the graph.

**Returns:**

* `tuple[BaseGraph, np.ndarray]` — A tuple containing: - The modified graph (same object, mutated in place) - A binary matrix of shape (num\_f, num\_e) where entry \[i, j] = 1 means f\_i depends on e\_j. For example, if row 0 is \[0, 1, 0, 1], then f0 = e1 XOR e3.
