Does anyone know how to work with SwitchCaseOp? I want to use it as a tool to execute conditioned circuits. I have read the documentation, however, I can not figure out how to use it and run it on a simulator. It will be a great asset if you can help me on the matter.
1 Answer
The example in https://qiskit.org/documentation/apidoc/qasm3.html explains how switch
works:
from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
qc = QuantumCircuit(qreg, creg)
qc.h([0, 1, 2])
qc.measure([0, 1, 2], [0, 1, 2])
with qc.switch(creg) as case:
with case(0):
qc.x(0)
with case(1, 2):
qc.z(1)
with case(case.DEFAULT):
qc.cx(0, 1)
qc.measure([0, 1, 2], [0, 1, 2])
However, it also has a note that says that its support is experimental as it depends on https://github.com/openqasm/openqasm/pull/463 . So simulators do not support it yet.
For this reason, the OpenQASM3 dumper needs the SWITCH_CASE_V1
experimental flag:
from qiskit import qasm3
qasm_string = qasm3.dumps(qc, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1)
print(qasm_string)
... # some of the output removed
c4[0] = measure q4[0];
c4[1] = measure q4[1];
c4[2] = measure q4[2];
switch_dummy = c4;
switch (switch_dummy) {
case 0: {
x q4[0];
}
break;
case 1:
case 2: {
z q4[1];
}
break;
default: {
cx q4[0], q4[1];
}
break;
}
A short explanation:
switch_dummy = c4; switch (switch_dummy)
: The switch condition is over the full classical registercase 0: {
: If the integer representation ofcreg
is0
.case 1:
andcase 2:
: Ifcreg
is a1
or a2
(considercreg
is a 3 bit-long signed integer).default:
This branch is for any other case.
-
$\begingroup$ Thank you so much for your attention to my question. It means the world to me. Just I do not know how the condition works here. For example with qc.if_test(), we can have a condition on the outcome of our measurement saved in a classical register. Then whether being 0 or 1, we apply arbitrary gates on the circuit. But here, how does the condition work? $\endgroup$ Oct 15 at 20:40
-
$\begingroup$ I added extra information using OpenQASM3 as a middle language. $\endgroup$– lucianoOct 16 at 6:40
-
$\begingroup$ Wow, that was a really great explanation. Thank you so much! $\endgroup$ Oct 17 at 16:02