Skip to content

Commit

Permalink
Fix the exact simulator to error on classical conditions (#200)
Browse files Browse the repository at this point in the history
Partially addresses #180

This also adds a test to make sure the simulator rejects a circuit
with classical control flow, for now.
  • Loading branch information
garrison authored May 25, 2023
1 parent 00b47fe commit f8fe41c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
6 changes: 5 additions & 1 deletion circuit_knitting_toolbox/utils/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ def simulate_statevector_outcomes(qc: QuantumCircuit, /) -> dict[int, float]:
current = defaultdict(list)
current[0].append((1.0, Statevector.from_int(0, 2**qc.num_qubits)))
for inst in qc.data:
if inst.operation.condition_bits:
raise ValueError(
"Operations conditioned on classical bits are currently not supported."
)
opname = inst.operation.name
if opname in ("measure", "reset"):
# The current instruction is not unitary: it's either a measurement
Expand Down Expand Up @@ -111,7 +115,7 @@ def simulate_statevector_outcomes(qc: QuantumCircuit, /) -> dict[int, float]:
if len(inst.clbits) != 0:
raise ValueError(
"Circuit cannot contain a non-measurement operation on classical bit(s)."
) # pragma: no cover
)
# Evolve each statevector according to the current instruction
for svs in current.values():
for _, sv in svs:
Expand Down
26 changes: 26 additions & 0 deletions test/utils/test_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,32 @@ def test_simulate_statevector_outcomes(self):
assert r[0] == pytest.approx(0.5)
assert r[1] == pytest.approx(0.5)

with self.subTest("Circuit with control flow"):
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
with pytest.raises(ValueError) as e_info:
simulate_statevector_outcomes(qc)
assert (
e_info.value.args[0]
== "Circuit cannot contain a non-measurement operation on classical bit(s)."
)

with self.subTest("Circuit with condition bits"):
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.measure(0, 0)
qc.x(1).c_if(0, True)
with pytest.raises(ValueError) as e_info:
simulate_statevector_outcomes(qc)
assert (
e_info.value.args[0]
== "Operations conditioned on classical bits are currently not supported."
)

def test_exact_sampler(self):
with self.subTest("Mid-circuit measurement, etc."):
qc = QuantumCircuit(2, 2)
Expand Down

0 comments on commit f8fe41c

Please sign in to comment.