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
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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354 | def parse_stim_circuit(stim_circuit: stim.Circuit) -> GraphBuilder:
"""Parse a stim circuit into a GraphBuilder.
Args:
stim_circuit: The stim circuit to convert.
Returns:
A GraphBuilder containing the ZX graph and all auxiliary data.
"""
builder = GraphBuilder()
for instruction in stim_circuit.flattened():
assert not isinstance(instruction, stim.CircuitRepeatBlock)
name = instruction.name
if name == "SHIFT_COORDS":
# TODO: handle visualization annotations in ZX diagrams
continue
if any(t.is_sweep_bit_target for t in instruction.targets_copy()):
raise NotImplementedError(
f"Sweep bit targets (e.g. sweep[N]) are not supported "
f"in instruction {str(instruction)!r}"
)
if name == "S" and is_t_tag(instruction.tag):
name = "T"
elif name == "S_DAG" and is_t_tag(instruction.tag):
name = "T_DAG"
# Handle parametric gates via tags (e.g., I with tag "R_Z(theta=0.3*pi)")
if name == "I" and instruction.tag:
result = parse_parametric_tag(instruction)
if result is not None:
gate_name, params = result
targets = [t.value for t in instruction.targets_copy()]
for qubit in targets:
if gate_name == "R_Z":
r_z(builder, qubit, params["theta"])
elif gate_name == "R_X":
r_x(builder, qubit, params["theta"])
elif gate_name == "R_Y":
r_y(builder, qubit, params["theta"])
elif gate_name == "U3":
u3(
builder,
qubit,
params["theta"],
params["phi"],
params["lambda"],
)
else:
raise ValueError(f"Unknown parametric gate: {gate_name}")
continue
if name == "TICK":
builder.tick()
continue
if name == "MPP":
args = instruction.gate_args_copy()
p = args[0] if args else 0
for paulis, invert in _iter_pauli_products(instruction):
mpp(builder, paulis, invert, p=p)
continue
if name in ("SPP", "SPP_DAG") and is_t_tag(instruction.tag):
is_dag = name == "SPP_DAG"
for paulis, invert in _iter_pauli_products(instruction):
tpp(builder, paulis, dagger=is_dag ^ invert)
continue
if name in ("SPP", "SPP_DAG") and instruction.tag:
parsed = parse_parametric_tag(instruction)
if parsed is not None and parsed[0] == "R_PAULI":
params = parsed[1]
_validate_r_pauli_targets(instruction)
is_dag = name == "SPP_DAG"
for paulis, invert in _iter_pauli_products(instruction):
r_pauli(builder, paulis, params["theta"], dagger=is_dag ^ invert)
continue
if name in ("SPP", "SPP_DAG"):
is_dag = name == "SPP_DAG"
for paulis, invert in _iter_pauli_products(instruction):
spp(builder, paulis, dagger=is_dag ^ invert)
continue
if name == "MPAD":
args = instruction.gate_args_copy()
p = args[0] if args else 0
for target in instruction.targets_copy():
mpad(builder, target.value, p=p)
continue
if name == "E" or name == "ELSE_CORRELATED_ERROR":
if name == "E":
builder.finalize_correlated_error()
targets = [t.value for t in instruction.targets_copy()]
types: list[Literal["X", "Y", "Z"]] = []
for t in instruction.targets_copy():
if t.is_x_target:
types.append("X")
elif t.is_y_target:
types.append("Y")
elif t.is_z_target:
types.append("Z")
else:
raise ValueError(f"Invalid target: {t}")
builder.correlated_error(targets, types, instruction.gate_args_copy()[0])
continue
if name == "DETECTOR":
targets = [t.value for t in instruction.targets_copy()]
builder.add_detector(targets)
continue
if name == "OBSERVABLE_INCLUDE":
targets_copy = instruction.targets_copy()
for t in targets_copy:
if not t.is_measurement_record_target:
raise ValueError(
f"OBSERVABLE_INCLUDE with Pauli targets is not "
f"supported in Tsim (only measurement record targets "
f"like rec[-1] are supported). Got instruction "
f"{str(instruction)!r}"
)
targets = [t.value for t in targets_copy]
args = instruction.gate_args_copy()
builder.include_observable(targets, int(args[0]))
continue
# instruction dispatch
if name not in GATE_TABLE:
raise ValueError(f"Unknown gate: {name}")
gate_func, num_qubits = GATE_TABLE[name]
targets = [t.value for t in instruction.targets_copy()]
invert = [t.is_inverted_result_target for t in instruction.targets_copy()]
is_classically_controlled = [
t.is_measurement_record_target for t in instruction.targets_copy()
]
args = instruction.gate_args_copy()
for i_target in range(0, len(targets), num_qubits):
chunk = targets[i_target : i_target + num_qubits]
cc_chunk = is_classically_controlled[i_target : i_target + num_qubits]
chunk_inverted = False
for j in range(num_qubits):
chunk_inverted ^= invert[i_target + j]
assert not (invert[i_target] and is_classically_controlled[i_target])
if chunk_inverted:
gate_func(builder, *chunk, *args, invert=True)
elif any(cc_chunk):
gate_func(builder, *chunk, *args, classically_controlled=cc_chunk)
else:
gate_func(builder, *chunk, *args)
builder.finalize_correlated_error()
# NOTE: materialize every observable id from 0..num_observables-1 so missing
# indices appear as deterministic-zero outputs, matching Stim semantics.
# Including no records into an existing observable does nothing.
for i in range(stim_circuit.num_observables):
builder.include_observable([], i)
return builder
|