1
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. $\endgroup$
    – Community Bot
    Oct 14, 2023 at 17:49

1 Answer 1

1
$\begingroup$

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:

  1. switch_dummy = c4; switch (switch_dummy): The switch condition is over the full classical register
  2. case 0: {: If the integer representation of creg is 0.
  3. case 1: and case 2:: If creg is a 1 or a 2 (consider creg is a 3 bit-long signed integer).
  4. default: This branch is for any other case.
$\endgroup$
3
  • $\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, 2023 at 20:40
  • $\begingroup$ I added extra information using OpenQASM3 as a middle language. $\endgroup$
    – luciano
    Oct 16, 2023 at 6:40
  • $\begingroup$ Wow, that was a really great explanation. Thank you so much! $\endgroup$ Oct 17, 2023 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.