{"cells":[{"cell_type":"markdown","id":"4d6203af-01d0-4362-a44c-66c2128e63d1","metadata":{},"source":["# Classical feedforward and control flow\n\nThis guide demonstrates the functionality available in the Qiskit SDK for performing classical feedforward and control flow. These features are sometimes referred to collectively as \"dynamic circuits.\" Classical feedforward refers to the ability to measure qubits in the middle of a circuit and perform additional quantum operations that depend on the measurement outcome. Qiskit supports four control flow constructs for classical feedforward, each implemented as a method on [`QuantumCircuit`](../api/qiskit/qiskit.circuit.QuantumCircuit). The constructs and their corresponding methods are:\n\n* If statement - [`QuantumCircuit.if_test`](../api/qiskit/qiskit.circuit.QuantumCircuit#if_test)\n\n* Switch statement - [`QuantumCircuit.switch`](../api/qiskit/qiskit.circuit.QuantumCircuit#switch)\n\n* For loop - [`QuantumCircuit.for_loop`](../api/qiskit/qiskit.circuit.QuantumCircuit#for_loop)\n\n* While loop - [`QuantumCircuit.while_loop`](../api/qiskit/qiskit.circuit.QuantumCircuit#while_loop)\n\nEach of these methods returns a [context manager](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers) and is typically used in a `with` statement. In the rest of this guide, we will explain each of these constructs and how to use them.\n\n\n There are some limitations of classical feedforward and control flow operations on quantum hardware that might impact your program. For more information, see [Hardware considerations and limitations for classical feedforward and control flow](./dynamic-circuits-considerations).\n \n\n## If statement\n\nThe if statement is used to conditionally perform operations based on the value of a classical bit or register.\n\nIn the example below, we apply a Hadamard gate to a qubit and measure it. If the result is 1, then we apply an X gate on the qubit, which has the effect of flipping it back to the 0 state. We then measure the qubit again. The resulting measurement outcome should be 0 with 100% probability.\n"]},{"cell_type":"code","execution_count":1,"id":"008f85d9-5b48-4e84-b250-846b07901607","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":1,"metadata":{},"output_type":"execute_result"}],"source":["from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister\n","\n","qubits = QuantumRegister(1)\n","clbits = ClassicalRegister(1)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0,) = qubits\n","(c0,) = clbits\n","\n","circuit.h(q0)\n","circuit.measure(q0, c0)\n","with circuit.if_test((c0, 1)):\n"," circuit.x(q0)\n","circuit.measure(q0, c0)\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'0': 1024}"]},{"cell_type":"markdown","id":"fdc99e4d-fcd0-4397-b6da-2e36a51f90a8","metadata":{},"source":["The `with` statement can be given an assignment target which is itself a context manager that can be stored and subsequently used to create an else block, which is executed whenever the contents of the if block are *not* executed.\n\nIn the example below, we initialize registers with two qubits and two classical bits. We apply a Hadamard gate to the first qubit and measure it. If the result is 1, then we apply a Hadamard gate on the second qubit; otherwise, we apply an X gate on the second qubit. Finally, we measure the second qubit as well.\n"]},{"cell_type":"code","execution_count":2,"id":"5b22ae93-27d1-4a0c-89e2-9f88383039d6","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":2,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(2)\n","clbits = ClassicalRegister(2)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0, q1) = qubits\n","(c0, c1) = clbits\n","\n","circuit.h(q0)\n","circuit.measure(q0, c0)\n","with circuit.if_test((c0, 1)) as else_:\n"," circuit.h(q1)\n","with else_:\n"," circuit.x(q1)\n","circuit.measure(q1, c1)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'01': 260, '11': 272, '10': 492}"]},{"cell_type":"markdown","id":"d70a3dec-33fe-4a2f-942e-592770c4868e","metadata":{},"source":["In addition to conditioning on a single classical bit, it's also possible to condition on the value of a classical register composed of multiple bits.\n\nIn the example below, we apply Hadamard gates to two qubits and measure them. If the result is `01`, that is, the first qubit is 1 and the second qubit is 0, then we apply an X gate to a third qubit. Finally, we measure the third qubit. Note that for clarity, we chose to specify the state of the third classical bit, which is 0, in the if condition. In the circuit drawing, the condition is indicated by the circles on the classical bits being conditioned on. A black circle indicates conditioning on 1, while a white circle indicates conditioning on 0.\n"]},{"cell_type":"code","execution_count":3,"id":"15ac9465-c61f-4de1-81e8-e4edfafb07b4","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":3,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(3)\n","clbits = ClassicalRegister(3)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0, q1, q2) = qubits\n","(c0, c1, c2) = clbits\n","\n","circuit.h([q0, q1])\n","circuit.measure(q0, c0)\n","circuit.measure(q1, c1)\n","with circuit.if_test((clbits, 0b001)):\n"," circuit.x(q2)\n","circuit.measure(q2, c2)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'101': 269, '011': 260, '000': 252, '010': 243}"]},{"cell_type":"markdown","id":"ce92fa5f-6b30-4b4c-aa37-5d894e4a40db","metadata":{},"source":["## Switch statement\n\nThe switch statement is used to select actions based on the value of a classical bit or register. It is similar to an if statement, but allows one to specify more cases for the branching logic. In the example below, we apply a Hadamard gate to a qubit and measure it. If the result is 0, we apply an X gate on the qubit, and if the result is 1, we apply a Z gate. The resulting measurement outcome should be 1 with 100% probability.\n"]},{"cell_type":"code","execution_count":4,"id":"6725ba53-c33e-479b-9413-ef3d55a8448c","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(1)\n","clbits = ClassicalRegister(1)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0,) = qubits\n","(c0,) = clbits\n","\n","circuit.h(q0)\n","circuit.measure(q0, c0)\n","with circuit.switch(c0) as case:\n"," with case(0):\n"," circuit.x(q0)\n"," with case(1):\n"," circuit.z(q0)\n","circuit.measure(q0, c0)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'1': 1024}"]},{"cell_type":"markdown","id":"a95e44eb-e54a-4ba7-bbc5-da0cc1f9df9a","metadata":{},"source":["Because the example above used a single classical bit, there were only two possible cases, so we could have achieved the same result using an if-else statement. The switch case is mainly useful when branching on the value of a classical register composed of multiple bits, as demonstrated in the following example. Here, we also show how to construct a default case, which is executed if none of the preceding cases are. Note that in a switch statement, only one of the blocks are ever executed. There is no fallthrough.\n\nIn the example below, we apply Hadamard gates to two qubits and measure them. If the result is either 00 or 11, we apply a Z gate to the third qubit. If the result is 01, we apply a Y gate. If none of the preceding cases matched, we apply an X gate. Finally, measure the third qubit.\n"]},{"cell_type":"code","execution_count":5,"id":"8bb350f1-fd66-4ef2-89b4-6168e6ad04b0","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":5,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(3)\n","clbits = ClassicalRegister(3)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0, q1, q2) = qubits\n","(c0, c1, c2) = clbits\n","\n","circuit.h([q0, q1])\n","circuit.measure(q0, c0)\n","circuit.measure(q1, c1)\n","with circuit.switch(clbits) as case:\n"," with case(0b000, 0b011):\n"," circuit.z(q2)\n"," with case(0b001):\n"," circuit.y(q2)\n"," with case(case.DEFAULT):\n"," circuit.x(q2)\n","circuit.measure(q2, c2)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'101': 267, '110': 249, '011': 265, '000': 243}"]},{"cell_type":"markdown","id":"be30c6ab-6aa6-4b06-8322-fecb9500ec6e","metadata":{},"source":["## For loop\n\nA for loop is used to iterate over a sequence of classical values and perform some operations during each iteration.\n\nIn the example below, we use a for loop to apply 5 X gates to a qubit and then measure it. Because we perform an odd number of X gates, the overall effect is to flip the qubit from the 0 state to the 1 state.\n"]},{"cell_type":"code","execution_count":6,"id":"af3ae593-b759-4b7b-86fc-9b6731a6cfd8","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":6,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(1)\n","clbits = ClassicalRegister(1)\n","circuit = QuantumCircuit(qubits, clbits)\n","(q0,) = qubits\n","(c0,) = clbits\n","\n","with circuit.for_loop(range(5)) as _:\n"," circuit.x(q0)\n","circuit.measure(q0, c0)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'1': 1024}"]},{"cell_type":"markdown","id":"6f1050b0-58a5-46e1-95c6-980db3f09c00","metadata":{},"source":["## While loop\n\nA while loop is used to repeat instructions while some condition is satisfied.\n\nIn the example below, we apply Hadamard gates to two qubits and measure them. Then, we create a while loop that repeats this procedure while the measurement outcome is 11. As a result, the final measurement should never be 11, with the remaining possibilities appearing with approximately equal frequency.\n"]},{"cell_type":"code","execution_count":7,"id":"95795aa7-9d4d-4c35-ba0e-48e6ba4f41b9","metadata":{},"outputs":[{"data":{"image/svg+xml":[" "],"text/plain":[""]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["qubits = QuantumRegister(2)\n","clbits = ClassicalRegister(2)\n","circuit = QuantumCircuit(qubits, clbits)\n","\n","q0, q1 = qubits\n","c0, c1 = clbits\n","\n","circuit.h([q0, q1])\n","circuit.measure(q0, c0)\n","circuit.measure(q1, c1)\n","with circuit.while_loop((clbits, 0b11)):\n"," circuit.h([q0, q1])\n"," circuit.measure(q0, c0)\n"," circuit.measure(q1, c1)\n","\n","circuit.draw(\"mpl\")\n","\n","# example output counts: {'01': 334, '10': 368, '00': 322}"]},{"cell_type":"markdown","id":"6aa76130-acc1-4479-8a54-edab6a133e7c","metadata":{},"source":["## Next steps\n\n\n * See an example of dynamic circuits in the [Repeat until success](https://learning.quantum.ibm.com/tutorial/repeat-until-success) tutorial.\n\n * Review the [circuit library API](/api/qiskit/circuit_library) reference.\n \n"]}],"metadata":{"description":"Use Qiskit for classical feedforward and control flow, otherwise referred to as dynamic circuits","kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3"},"title":"Classical feedforward and control flow (a.k.a. dynamic circuits)"},"nbformat":4,"nbformat_minor":2}