Skip to content

Experimental

Helpers outside of the stable API. They may change or be removed in any release.

Computes measurement probabilities for a given state.

Uses joint decomposition [0, n] where: - compiled_scalar_graphs[0]: normalization (0 outputs plugged) - compiled_scalar_graphs[1]: full joint probability (all outputs plugged)

Parameters:

Name Type Description Default
circuit Circuit

The quantum circuit to compile.

required
sample_detectors bool

If True, compute detector/observable probabilities.

False
strategy SamplingStrategy

Stabilizer rank decomposition strategy ("cat5", "bss", "cutting"); "active_statevector" cannot compute probabilities.

'cat5'
seed int | None

Random seed. If None, a random seed is generated. Results are only deterministic for a fixed batch size, the same versions of Tsim and its dependencies (such as NumPy and JAX) and the same backend (CPU or GPU).

None
Source code in src/tsim/sampler.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
def __init__(
    self,
    circuit: Circuit,
    *,
    sample_detectors: bool = False,
    strategy: SamplingStrategy = "cat5",
    seed: int | None = None,
):
    """Create a probability estimator.

    Args:
        circuit: The quantum circuit to compile.
        sample_detectors: If True, compute detector/observable probabilities.
        strategy: Stabilizer rank decomposition strategy ("cat5", "bss",
            "cutting"); "active_statevector" cannot compute probabilities.
        seed: Random seed. If None, a random seed is generated. Results are
            only deterministic for a fixed batch size, the same versions of
            Tsim and its dependencies (such as NumPy and JAX) and the same
            backend (CPU or GPU).

    """
    super().__init__(
        circuit,
        sample_detectors=sample_detectors,
        mode="joint",
        seed=seed,
        strategy=strategy,
    )

__repr__

__repr__() -> str

Return a string representation with compilation statistics.

Source code in src/tsim/sampler.py
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def __repr__(self) -> str:
    """Return a string representation with compilation statistics."""
    n_direct = len(self._program.direct_f_indices)

    c_graphs = []
    c_params = []
    c_a_terms = []
    c_b_terms = []
    c_c_terms = []
    c_d_terms = []
    c_e_terms = []
    total_memory_bytes = 0
    num_outputs = []
    statevector_widths: list[int] = []
    statevector_actions = 0

    for component in self._program.components:
        if isinstance(component, StatevectorComponent):
            statevector_widths.append(component.width)
            statevector_actions += component.num_actions
            num_outputs.append(len(component.output_indices))
            total_memory_bytes += _nbytes(component)
            continue
        for circuit in component.compiled_scalar_graphs:
            num_outputs.append(len(component.output_indices))
            c_graphs.append(circuit.num_graphs)
            c_params.append(circuit.n_params)
            c_a_terms.append(circuit.node_phases.phases.size)
            c_b_terms.append(circuit.phase_terms.coeffs.size)
            c_c_terms.append(
                circuit.pi_products.psi_params.shape[0]
                * circuit.pi_products.psi_params.shape[1]
            )
            c_d_terms.append(
                circuit.phase_pairs.alpha.size + circuit.phase_pairs.beta.size
            )
            c_e_terms.append(
                circuit.float_terms.table.shape[0]
                * circuit.float_terms.table.shape[1]
            )

            total_memory_bytes += _nbytes(circuit)

    def _format_bytes(n: int) -> str:
        if n < 1024:
            return f"{n} B"
        if n < 1024**2:
            return f"{n / 1024:.1f} kB"
        return f"{n / (1024**2):.1f} MB"

    total_memory_str = _format_bytes(total_memory_bytes)
    error_channel_bits = sum(
        channel.num_bits for channel in self._channel_sampler.channels
    )

    # NOTE: only the statistics of the backends in use are shown.
    parts = [f"{n_direct} direct"]
    if statevector_widths:
        parts.append(
            f"{len(statevector_widths)} statevector components "
            f"(width ≤ {max(statevector_widths)}, "
            f"{statevector_actions} actions)"
        )
    if c_graphs:
        parts.append(f"{sum(c_graphs)} graphs")
    parts += [
        f"{error_channel_bits} error channel bits",
        f"{max(num_outputs, default=0)} outputs for largest cc",
    ]
    if c_graphs:
        parts += [
            f"≤ {max(c_params)} parameters",
            f"{sum(c_a_terms)} A terms",
            f"{sum(c_b_terms)} B terms",
            f"{sum(c_c_terms)} C terms",
            f"{sum(c_d_terms)} D terms",
            f"{sum(c_e_terms)} E terms",
        ]
    parts.append(total_memory_str)
    return f"{type(self).__name__}({', '.join(parts)})"

probability_of

probability_of(
    state: ndarray, *, batch_size: int
) -> np.ndarray

Compute probabilities for a batch of error samples given a measurement state.

Parameters:

Name Type Description Default
state ndarray

The measurement outcome state to compute probability for.

required
batch_size int

Number of error samples to use for estimation.

required

Returns:

Type Description
ndarray

Array of probabilities P(state | error_sample) for each error sample.

Source code in src/tsim/sampler.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
def probability_of(self, state: np.ndarray, *, batch_size: int) -> np.ndarray:
    """Compute probabilities for a batch of error samples given a measurement state.

    Args:
        state: The measurement outcome state to compute probability for.
        batch_size: Number of error samples to use for estimation.

    Returns:
        Array of probabilities P(state | error_sample) for each error sample.

    """
    if batch_size < 1:
        raise ValueError(f"batch_size must be at least 1, got {batch_size}")
    expected_outputs = self._program.num_outputs
    if state.shape != (expected_outputs,):
        raise ValueError(
            f"state must have shape ({expected_outputs},), got {state.shape}"
        )
    f_samples = jnp.asarray(self._channel_sampler.sample(batch_size))
    p_norm = jnp.ones(batch_size)
    p_joint = jnp.ones(batch_size)

    if len(self._program.direct_f_indices) > 0:
        direct_bits = _direct_bits(self._program, f_samples)
        n_direct = len(self._program.direct_f_indices)
        targets = state[self._program.output_order[:n_direct]]
        p_joint = p_joint * (direct_bits == targets).all(axis=1)

    for component in self._program.components:
        assert isinstance(component, CompiledComponent)
        assert len(component.compiled_scalar_graphs) == 2

        f_selected = f_samples[:, component.f_selection]

        norm_circuit, joint_circuit = component.compiled_scalar_graphs

        # Normalization: only f-params
        p_norm = p_norm * jnp.abs(evaluate(norm_circuit, f_selected))

        # Joint probability: f-params + state
        component_state = state[list(component.output_indices)]
        tiled_state = jnp.tile(component_state, (batch_size, 1))
        joint_params = jnp.hstack([f_selected, tiled_state])
        p_joint = p_joint * jnp.abs(evaluate(joint_circuit, joint_params))

    return np.asarray(p_joint / p_norm)

Transversal encoder for the [[7,1,3]] Steane code.

Source code in src/tsim/utils/encoder.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def __init__(self):
    """Initialize the Steane code encoder."""
    encoding_program = """
    R 0 1 2 3 4 5
    TICK
    SQRT_Y_DAG 0 1 2 3 4 5
    TICK
    CZ 1 2 3 4 5 6
    TICK
    SQRT_Y 6
    TICK
    CZ 0 3 2 5 4 6
    TICK
    SQRT_Y 2 3 4 5 6
    TICK
    CZ 0 1 2 3 4 5
    TICK
    SQRT_Y 1 2 4
    TICK
    X 3
    Z 5 1
    TICK
    """
    super().__init__(
        n=7,
        encoding_qubit=6,
        encoding_program_text=encoding_program,
        stabilizer_generators=[[0, 1, 2, 3], [1, 2, 4, 5], [2, 3, 4, 6]],
        observables=[[0, 1, 5]],
    )

diagram

diagram(**kwargs)

Return a timeline-svg diagram of the encoded circuit.

Source code in src/tsim/utils/encoder.py
167
168
169
def diagram(self, **kwargs):
    """Return a timeline-svg diagram of the encoded circuit."""
    return self.circuit.diagram("timeline-svg", **kwargs)

encode_transversally

encode_transversally(program_text: str) -> None

Encode a program transversally by replacing physicalgates with transversal gates.

Transform a program on m qubits into a program on n * m qubits (consisting of n code blocks).

Parameters:

Name Type Description Default
program_text str

The program to encode transversally.

required
Source code in src/tsim/utils/encoder.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def encode_transversally(self, program_text: str) -> None:
    """Encode a program transversally by replacing  physicalgates with transversal gates.

    Transform a program on m qubits into a program on n * m qubits (consisting of n code blocks).

    Args:
        program_text: The program to encode transversally.

    """
    mod_circ = _transform_circuit(
        program_text,
        stride=self.n,
        offsets=list(range(self.n)),
        stabilizer_generators=self.stabilizer_generators,
        observables=self.observables,
    )
    self.circuit.append_from_stim_program_text(str(mod_circ))

encoding_flow_generators

encoding_flow_generators()

Return the Pauli flow generators for the encoding circuit.

Source code in src/tsim/utils/encoder.py
171
172
173
174
def encoding_flow_generators(self):
    """Return the Pauli flow generators for the encoding circuit."""
    assert self.encoding_program_text is not None
    return stim.Circuit(self.encoding_program_text).flow_generators()

initialize

initialize(
    program_text: str,
    encoding_program_text: str | None = None,
) -> None

Initialize state preparation and apply encoding circuit.

Apply the state preparation program for k qubits, then apply an encoding circuit to encode the state into n qubits.

Parameters:

Name Type Description Default
program_text str

The state preparation program for k qubits. Generally, this should be a simple program that prepares each of the k qubits in a single-qubit state.

required
encoding_program_text optional

An encoding circuit for a single logical qubit. This should encode a single logical qubit at input self.encoding_qubit into a state of n qubits. If not provided, the encoder will use a noiseless default encoding.

None
Source code in src/tsim/utils/encoder.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def initialize(
    self, program_text: str, encoding_program_text: str | None = None
) -> None:
    """Initialize state preparation and apply encoding circuit.

    Apply the state preparation program for k qubits, then apply an encoding
    circuit to encode the state into n qubits.

    Args:
        program_text: The state preparation program for k qubits. Generally, this
            should be a simple program that prepares each of the k qubits in a
            single-qubit state.
        encoding_program_text (optional): An encoding circuit for a single logical
            qubit. This should encode a single logical qubit at input
            `self.encoding_qubit` into a state of n qubits.
            If not provided, the encoder will use a noiseless default encoding.

    """
    encoding = encoding_program_text or self.encoding_program_text
    if not encoding:
        raise ValueError("Encoding program text is required")

    mod_circ = _transform_circuit(
        program_text,
        stride=self.n,
        offsets=[self.encoding_qubit],
        used_qubits=self.used_qubits,
        stabilizer_generators=self.stabilizer_generators,
        observables=self.observables,
    )

    self.circuit.append_from_stim_program_text(str(mod_circ))
    self.circuit.append_from_stim_program_text(
        str(
            _transform_circuit(
                encoding,
                stride=1,
                offsets=[self.n * off for off in sorted(self.used_qubits)],
                stabilizer_generators=self.stabilizer_generators,
                observables=self.observables,
            )
        )
    )

Transversal encoder for the [[17,1,5]] 2D color code.

Source code in src/tsim/utils/encoder.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def __init__(self):
    """Initialize the color code encoder."""
    encoding_program = """
    R 0 1 2 3 4 5 6 8 9 10 11 12 13 14 15 16
    SQRT_Y 0 1 2 3 4 5 6 8 9 10 11 12 13 14 15 16
    TICK
    CZ 1 3 7 10 12 14 13 16
    TICK
    SQRT_Y_DAG 7 16
    TICK
    CZ 4 7 8 10 11 14 15 16
    TICK
    SQRT_Y_DAG 4 10 14 16
    TICK
    CZ 2 4 6 8 7 9 10 13
    CZ 14 16
    TICK
    SQRT_Y 3 6 9 10 12 13
    TICK
    CZ 0 2 3 6 5 8 10 12 11 13
    TICK
    SQRT_Y 1 2 3 4 6 7 8 9 11 12 14
    TICK
    CZ 0 1 2 3 4 5 6 7 8 9 12 15
    TICK
    SQRT_Y_DAG 0 2 5 6 8 10 12
    X 14 7 5 2 1 4
    Z 11 6 4 2
    """
    stabs = [
        [0, 1, 2, 3],
        [0, 2, 4, 5],
        [4, 5, 6, 7],
        [6, 7, 8, 9],
        [11, 13, 14, 16],
        [10, 11, 12, 14],
        [12, 14, 15, 16],
        [2, 3, 5, 6, 8, 10, 11, 13],
    ]
    obs = [[1, 3, 10, 12, 15]]
    super().__init__(
        n=17,
        encoding_qubit=7,
        encoding_program_text=encoding_program,
        stabilizer_generators=stabs,
        observables=obs,
    )

diagram

diagram(**kwargs)

Return a timeline-svg diagram of the encoded circuit.

Source code in src/tsim/utils/encoder.py
167
168
169
def diagram(self, **kwargs):
    """Return a timeline-svg diagram of the encoded circuit."""
    return self.circuit.diagram("timeline-svg", **kwargs)

encode_transversally

encode_transversally(program_text: str) -> None

Encode a program transversally by replacing physicalgates with transversal gates.

Transform a program on m qubits into a program on n * m qubits (consisting of n code blocks).

Parameters:

Name Type Description Default
program_text str

The program to encode transversally.

required
Source code in src/tsim/utils/encoder.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def encode_transversally(self, program_text: str) -> None:
    """Encode a program transversally by replacing  physicalgates with transversal gates.

    Transform a program on m qubits into a program on n * m qubits (consisting of n code blocks).

    Args:
        program_text: The program to encode transversally.

    """
    mod_circ = _transform_circuit(
        program_text,
        stride=self.n,
        offsets=list(range(self.n)),
        stabilizer_generators=self.stabilizer_generators,
        observables=self.observables,
    )
    self.circuit.append_from_stim_program_text(str(mod_circ))

encoding_flow_generators

encoding_flow_generators()

Return the Pauli flow generators for the encoding circuit.

Source code in src/tsim/utils/encoder.py
171
172
173
174
def encoding_flow_generators(self):
    """Return the Pauli flow generators for the encoding circuit."""
    assert self.encoding_program_text is not None
    return stim.Circuit(self.encoding_program_text).flow_generators()

initialize

initialize(
    program_text: str,
    encoding_program_text: str | None = None,
) -> None

Initialize state preparation and apply encoding circuit.

Apply the state preparation program for k qubits, then apply an encoding circuit to encode the state into n qubits.

Parameters:

Name Type Description Default
program_text str

The state preparation program for k qubits. Generally, this should be a simple program that prepares each of the k qubits in a single-qubit state.

required
encoding_program_text optional

An encoding circuit for a single logical qubit. This should encode a single logical qubit at input self.encoding_qubit into a state of n qubits. If not provided, the encoder will use a noiseless default encoding.

None
Source code in src/tsim/utils/encoder.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def initialize(
    self, program_text: str, encoding_program_text: str | None = None
) -> None:
    """Initialize state preparation and apply encoding circuit.

    Apply the state preparation program for k qubits, then apply an encoding
    circuit to encode the state into n qubits.

    Args:
        program_text: The state preparation program for k qubits. Generally, this
            should be a simple program that prepares each of the k qubits in a
            single-qubit state.
        encoding_program_text (optional): An encoding circuit for a single logical
            qubit. This should encode a single logical qubit at input
            `self.encoding_qubit` into a state of n qubits.
            If not provided, the encoder will use a noiseless default encoding.

    """
    encoding = encoding_program_text or self.encoding_program_text
    if not encoding:
        raise ValueError("Encoding program text is required")

    mod_circ = _transform_circuit(
        program_text,
        stride=self.n,
        offsets=[self.encoding_qubit],
        used_qubits=self.used_qubits,
        stabilizer_generators=self.stabilizer_generators,
        observables=self.observables,
    )

    self.circuit.append_from_stim_program_text(str(mod_circ))
    self.circuit.append_from_stim_program_text(
        str(
            _transform_circuit(
                encoding,
                stride=1,
                offsets=[self.n * off for off in sorted(self.used_qubits)],
                stabilizer_generators=self.stabilizer_generators,
                observables=self.observables,
            )
        )
    )