Skip to content

program_text

Conversion utilities between tsim shorthand and stim program text.

controlled_gate_decomposition_lines

controlled_gate_decomposition_lines(
    gate: str,
    control1: int | str,
    control2: int | str,
    target: int | str,
    *,
    tag: str = ""
) -> list[str]

Return a Clifford+T decomposition for a controlled-controlled gate.

Source code in src/tsim/utils/program_text.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def controlled_gate_decomposition_lines(
    gate: str,
    control1: int | str,
    control2: int | str,
    target: int | str,
    *,
    tag: str = "",
) -> list[str]:
    """Return a Clifford+T decomposition for a controlled-controlled gate."""
    if gate not in ("CCZ", "CCX"):
        raise ValueError(f"Unsupported controlled-controlled gate: {gate!r}")

    def tagged(name: str) -> str:
        return f"{name}[{tag}]" if tag else name

    a, b, c = str(control1), str(control2), str(target)
    ccz_lines = [
        f"{tagged('CNOT')} {b} {c}",
        f"{tagged('T_DAG')} {c}",
        f"{tagged('CNOT')} {a} {c}",
        f"{tagged('T')} {c}",
        f"{tagged('CNOT')} {b} {c}",
        f"{tagged('T_DAG')} {c}",
        f"{tagged('CNOT')} {a} {c}",
        f"{tagged('T')} {b}",
        f"{tagged('T')} {c}",
        f"{tagged('CNOT')} {a} {b}",
        f"{tagged('T')} {a}",
        f"{tagged('T_DAG')} {b}",
        f"{tagged('CNOT')} {a} {b}",
    ]
    if gate == "CCZ":
        return ccz_lines
    return [f"{tagged('H')} {c}", *ccz_lines, f"{tagged('H')} {c}"]

enriched_stim_error

enriched_stim_error(
    exc: ValueError, converted_text: str
) -> ValueError

Improve stim parse errors for tsim-specific gates.

When stim raises a 'Gate not found' error for a gate that should have been converted by shorthand_to_stim, this searches the converted text for the unconverted usage and returns a more helpful error message.

Source code in src/tsim/utils/program_text.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def enriched_stim_error(exc: ValueError, converted_text: str) -> ValueError:
    """Improve stim parse errors for tsim-specific gates.

    When stim raises a 'Gate not found' error for a gate that should have been
    converted by shorthand_to_stim, this searches the converted text for the
    unconverted usage and returns a more helpful error message.
    """
    m = _GATE_NOT_FOUND_RE.search(str(exc))
    if not m or m.group(1) not in _TSIM_GATES:
        return exc
    # Successfully converted gates live inside brackets (e.g. I[R_Z(...)]) and won't match.
    usage = _GATE_USAGE_RE.search(converted_text)
    if not usage:
        return exc
    return ValueError(f"Could not parse '{usage.group()}' in program text.")

shorthand_to_stim

shorthand_to_stim(text: str) -> str

Convert tsim shorthand syntax to valid stim instructions.

Converts

CCZ 0 1 2 → Clifford+T decomposition of CCZ CCX 0 1 2 → Clifford+T decomposition of CCX/Toffoli T 0 1 → S[T] 0 1 T_DAG 0 1 → S_DAG[T] 0 1 TPP X0Y1 → SPP[T] X0Y1 TPP_DAG X0Y1 → SPP_DAG[T] X0Y1 R_Z(0.3) 0 → I[R_Z(theta=0.3pi)] 0 R_X(0.25) 0 → I[R_X(theta=0.25pi)] 0 R_Y(-0.5) 0 → I[R_Y(theta=-0.5pi)] 0 R_XX(0.5) 0 1 → SPP[R_PAULI(theta=0.5pi)] X0X1 R_YY(0.5) 0 1 → SPP[R_PAULI(theta=0.5pi)] Y0Y1 R_ZZ(0.5) 0 1 → SPP[R_PAULI(theta=0.5pi)] Z0Z1 R_PAULI(0.3) X0Y1 → SPP[R_PAULI(theta=0.3pi)] X0Y1 U3(0.3, 0.24, 0.49) 0 → I[U3(theta=0.3pi, phi=0.24pi, lambda=0.49*pi)] 0

Source code in src/tsim/utils/program_text.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def shorthand_to_stim(text: str) -> str:
    """Convert tsim shorthand syntax to valid stim instructions.

    Converts:
        CCZ 0 1 2           → Clifford+T decomposition of CCZ
        CCX 0 1 2           → Clifford+T decomposition of CCX/Toffoli
        T 0 1               → S[T] 0 1
        T_DAG 0 1           → S_DAG[T] 0 1
        TPP X0*Y1           → SPP[T] X0*Y1
        TPP_DAG X0*Y1       → SPP_DAG[T] X0*Y1
        R_Z(0.3) 0          → I[R_Z(theta=0.3*pi)] 0
        R_X(0.25) 0         → I[R_X(theta=0.25*pi)] 0
        R_Y(-0.5) 0         → I[R_Y(theta=-0.5*pi)] 0
        R_XX(0.5) 0 1       → SPP[R_PAULI(theta=0.5*pi)] X0*X1
        R_YY(0.5) 0 1       → SPP[R_PAULI(theta=0.5*pi)] Y0*Y1
        R_ZZ(0.5) 0 1       → SPP[R_PAULI(theta=0.5*pi)] Z0*Z1
        R_PAULI(0.3) X0*Y1  → SPP[R_PAULI(theta=0.3*pi)] X0*Y1
        U3(0.3, 0.24, 0.49) 0 → I[U3(theta=0.3*pi, phi=0.24*pi, lambda=0.49*pi)] 0

    """
    text = _expand_controlled_gates(text)

    # TPP_DAG/TPP must come before T_DAG/T to avoid partial matches
    # (?<!\[) ensures we don't match T inside [T]
    text = re.sub(
        r"(?<!\[)\bTPP_DAG(?:\[([^\]\n]*)\])?(?!\w)",
        _replace_t_family("SPP_DAG"),
        text,
    )
    text = re.sub(
        r"(?<!\[)\bTPP(?:\[([^\]\n]*)\])?(?!\w)",
        _replace_t_family("SPP"),
        text,
    )
    text = re.sub(
        r"(?<!\[)\bT_DAG(?:\[([^\]\n]*)\])?(?!\w)",
        _replace_t_family("S_DAG"),
        text,
    )
    text = re.sub(
        r"(?<!\[)\bT(?:\[([^\]\n]*)\])?(?!\w)",
        _replace_t_family("S"),
        text,
    )

    def replace_pauli_pair(m: re.Match) -> str:
        pauli = m.group(1)
        alpha = float(m.group(2))
        q0, q1 = m.group(3), m.group(4)
        if q0 == q1:
            raise ValueError(
                f"R_{pauli}{pauli} target qubits must be distinct, got {q0} {q1}."
            )
        return f"SPP[R_PAULI(theta={alpha}*pi)] {pauli}{q0}*{pauli}{q1}"

    text = re.sub(
        rf"\bR_([XYZ])\1\(({FLOAT_RE})\)\s+(\d+)\s+(\d+)", replace_pauli_pair, text
    )

    def replace_pauli(m: re.Match) -> str:
        alpha = float(m.group(1))
        return f"SPP[R_PAULI(theta={alpha}*pi)] {m.group(2)}"

    text = re.sub(
        rf"\bR_PAULI\(({FLOAT_RE})\)\s+((?:[XYZ]\d+)(?:\*[XYZ]\d+)*)",
        replace_pauli,
        text,
    )

    def replace_rotation(m: re.Match) -> str:
        axis = m.group(1)
        return f"I[R_{axis}(theta={float(m.group(2))}*pi)]"

    text = re.sub(rf"\bR_([XYZ])\(({FLOAT_RE})\)", replace_rotation, text)

    def replace_u3(m: re.Match) -> str:
        theta, phi, lam = float(m.group(1)), float(m.group(2)), float(m.group(3))
        return f"I[U3(theta={theta}*pi, phi={phi}*pi, lambda={lam}*pi)]"

    text = re.sub(
        rf"\bU3\(({FLOAT_RE})\s*,\s*({FLOAT_RE})\s*,\s*({FLOAT_RE})\)",
        replace_u3,
        text,
    )

    # Canonicalize literals inside already-expanded parametric tags so that
    # equivalent inputs like `I[R_X(theta=0.5e-2*pi)]` and
    # `I[R_X(theta=0.005*pi)]` produce the same stim tag string. This keeps
    # `tsim.Circuit(str(c)) == c` round-trip stable across notations.
    def _canonicalize_param(m: re.Match) -> str:
        return f"{m.group(1)}={float(m.group(2))}*pi"

    text = re.sub(
        rf"\b(theta|phi|lambda)=({FLOAT_RE})\*pi",
        _canonicalize_param,
        text,
    )

    return text

stim_to_shorthand

stim_to_shorthand(text: str) -> str

Convert expanded stim annotations back to tsim shorthand.

Rewrites: - I[U3(theta=θpi, phi=φpi, lambda=λpi)] → U3(θ, φ, λ) - I[R_X(theta=αpi)] / I[R_Y(...)] / I[R_Z(...)] → R_X(α) / R_Y(α) / R_Z(α) - SPP[R_PAULI(theta=αpi)] P0P1 → R_PP(α) 0 1 (P ∈ {X, Y, Z}) - SPP[R_PAULI(theta=αpi)] X0Y1 → R_PAULI(α) X0*Y1 - SPP[T] → TPP - SPP_DAG[T] → TPP_DAG - S[T] → T - S_DAG[T] → T_DAG

Source code in src/tsim/utils/program_text.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def stim_to_shorthand(text: str) -> str:
    """Convert expanded stim annotations back to tsim shorthand.

    Rewrites:
    - I[U3(theta=θ*pi, phi=φ*pi, lambda=λ*pi)] → U3(θ, φ, λ)
    - I[R_X(theta=α*pi)] / I[R_Y(...)] / I[R_Z(...)] → R_X(α) / R_Y(α) / R_Z(α)
    - SPP[R_PAULI(theta=α*pi)] P0*P1 → R_PP(α) 0 1 (P ∈ {X, Y, Z})
    - SPP[R_PAULI(theta=α*pi)] X0*Y1 → R_PAULI(α) X0*Y1
    - SPP[T] → TPP
    - SPP_DAG[T] → TPP_DAG
    - S[T] → T
    - S_DAG[T] → T_DAG
    """

    # Replace I[U3(theta=θ*pi, phi=φ*pi, lambda=λ*pi)] with U3(θ, φ, λ)
    def replace_u3(m: re.Match) -> str:
        theta, phi, lam = m.group(1), m.group(2), m.group(3)
        return f"U3({theta}, {phi}, {lam})"

    text = re.sub(
        rf"\bI\[U3\(theta=({FLOAT_RE})\*pi, phi=({FLOAT_RE})\*pi, lambda=({FLOAT_RE})\*pi\)\]",
        replace_u3,
        text,
    )

    # SPP[R_PAULI(...)] with a same-axis two-qubit product → R_XX/R_YY/R_ZZ shorthand.
    # Must precede the general R_PAULI rewrite below.
    def replace_pauli_pair(m: re.Match) -> str:
        alpha, pauli, q0, q1 = m.group(1), m.group(2), m.group(3), m.group(4)
        return f"R_{pauli}{pauli}({alpha}) {q0} {q1}"

    text = re.sub(
        rf"\bSPP\[R_PAULI\(theta=({FLOAT_RE})\*pi\)\] ([XYZ])(\d+)\*\2(\d+)(?!\*)\b",
        replace_pauli_pair,
        text,
    )

    def replace_pauli(m: re.Match) -> str:
        alpha, product = m.group(1), m.group(2)
        return f"R_PAULI({alpha}) {product}"

    text = re.sub(
        rf"\bSPP\[R_PAULI\(theta=({FLOAT_RE})\*pi\)\] ((?:[XYZ]\d+)(?:\*[XYZ]\d+)*)",
        replace_pauli,
        text,
    )

    # Replace I[R_X(...)] / I[R_Y(...)] / I[R_Z(...)] with R_X(α) / R_Y(α) / R_Z(α)
    def replace_rotation(m: re.Match) -> str:
        axis = m.group(1)
        angle = m.group(2)
        return f"R_{axis}({angle})"

    text = re.sub(
        rf"\bI\[R_([XYZ])\(theta=({FLOAT_RE})\*pi\)\]",
        replace_rotation,
        text,
    )

    # Replace SPP[T] and SPP_DAG[T] with TPP and TPP_DAG
    # Must come before S[T]/S_DAG[T] to avoid partial matches
    text = re.sub(
        r"(?<!\w)SPP_DAG\[(T(?::[^\]\n]*)?)\](?!\w)",
        _replace_t_family_shorthand("TPP_DAG"),
        text,
    )
    text = re.sub(
        r"(?<!\w)SPP\[(T(?::[^\]\n]*)?)\](?!\w)",
        _replace_t_family_shorthand("TPP"),
        text,
    )

    # Replace S[T] and S_DAG[T] with T and T_DAG
    # Use non-word lookarounds because trailing ] is not a word character.
    text = re.sub(
        r"(?<!\w)S_DAG\[(T(?::[^\]\n]*)?)\](?!\w)",
        _replace_t_family_shorthand("T_DAG"),
        text,
    )
    text = re.sub(
        r"(?<!\w)S\[(T(?::[^\]\n]*)?)\](?!\w)",
        _replace_t_family_shorthand("T"),
        text,
    )

    return text