Skip to content

Commit 79ae4f1

Browse files
fix touched() function in LayerTag (#1092)
Ensures that circuit instructions that are tagged with more than one target group are identified correctly with `def touched()` in `LayerTag` of `stimflow`.
1 parent 915166e commit 79ae4f1

2 files changed

Lines changed: 59 additions & 3 deletions

File tree

glue/stimflow/src/stimflow/_layers/_layer_tag.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,17 @@ def copy(self) -> LayerTag:
1515
return LayerTag(circuit=self.circuit)
1616

1717
def touched(self) -> set[int]: # set of qubit touched by it
18-
tagged_gate_targets = self.circuit[0].target_groups()[0]
19-
return {gate_target.qubit_value for gate_target in tagged_gate_targets}
18+
stack = [self.circuit[0]]
19+
out = set()
20+
while stack:
21+
cur = stack.pop()
22+
if isinstance(cur, stim.CircuitRepeatBlock):
23+
stack.extend(cur.body_copy())
24+
else:
25+
for target in cur.targets_copy():
26+
if target.is_qubit_target:
27+
out.add(target.qubit_value)
28+
return out
2029

2130
def to_z_basis(self) -> list[Layer]:
2231
return [self]

glue/stimflow/src/stimflow/_layers/_layer_tag_test.py

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import stim
44

55
import stimflow
6-
6+
from stimflow._layers._layer_tag import LayerTag
77

88
def test_survives_transpile():
99
circuit = stim.Circuit(
@@ -56,3 +56,50 @@ def test_survives_transpile():
5656
DETECTOR rec[-1] rec[-2]
5757
"""
5858
)
59+
60+
def test_touched() -> None:
61+
62+
layer_cx = LayerTag(circuit=stim.Circuit("CX 0 1 2 3"))
63+
assert layer_cx.touched() == {0, 1, 2, 3}
64+
65+
layer_m = LayerTag(circuit=stim.Circuit("M 0 1 2"))
66+
assert layer_m.touched() == {0, 1, 2}
67+
68+
# Test filtering of non-qubit targets (e.g. combiners in MPP instructions or Pauli targets).
69+
layer_mpp = LayerTag(circuit=stim.Circuit("MPP X10*Y11 Z12*X13"))
70+
# In MPP, targets are Pauli targets/combiners.
71+
# We verify touched() handles target groups gracefully.
72+
assert isinstance(layer_mpp.touched(), set)
73+
74+
# Test that when self.circuit[0] is a CircuitRepeatBlock, touched() iterates
75+
# through the block and finds all qubit targets.
76+
layer_repeat = LayerTag(
77+
circuit=stim.Circuit(
78+
"""
79+
REPEAT 5 {
80+
CX 0 1
81+
TICK
82+
M 2 3
83+
}
84+
"""
85+
)
86+
)
87+
assert layer_repeat.touched() == {0, 1, 2, 3}
88+
89+
# Test that when self.circuit[0] contains nested CircuitRepeatBlocks, touched()
90+
# recursively iterates through all nested repeat blocks to find all qubit targets.
91+
layer_nested_repeat = LayerTag(
92+
circuit=stim.Circuit(
93+
"""
94+
REPEAT 3 {
95+
CX 0 1
96+
REPEAT 2 {
97+
CX 2 3
98+
TICK
99+
M 4 5
100+
}
101+
}
102+
"""
103+
)
104+
)
105+
assert layer_nested_repeat.touched() == {0, 1, 2, 3, 4, 5}

0 commit comments

Comments
 (0)