/
while_loop.py
163 lines (130 loc) · 5.74 KB
/
while_loop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Circuit operation representing a ``while`` loop."""
from __future__ import annotations
from typing import TYPE_CHECKING
from qiskit.circuit.classicalregister import Clbit, ClassicalRegister
from qiskit.circuit.classical import expr
from qiskit.circuit.exceptions import CircuitError
from ._builder_utils import validate_condition, condition_resources
from .control_flow import ControlFlowOp
if TYPE_CHECKING:
from qiskit.circuit import QuantumCircuit
class WhileLoopOp(ControlFlowOp):
"""A circuit operation which repeatedly executes a subcircuit (``body``) until
a condition (``condition``) evaluates as False.
The classical bits used in ``condition`` must be a subset of those attached
to ``body``.
"""
def __init__(
self,
condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | expr.Expr,
body: QuantumCircuit,
label: str | None = None,
):
"""
Args:
condition: A condition to be checked prior to executing ``body``. Can be
specified as either a tuple of a ``ClassicalRegister`` to be tested
for equality with a given ``int``, or as a tuple of a ``Clbit`` to
be compared to either a ``bool`` or an ``int``.
body: The loop body to be repeatedly executed.
label: An optional label for identifying the instruction.
"""
num_qubits = body.num_qubits
num_clbits = body.num_clbits
super().__init__("while_loop", num_qubits, num_clbits, [body], label=label)
self.condition = validate_condition(condition)
@property
def params(self):
return self._params
@params.setter
def params(self, parameters):
# pylint: disable=cyclic-import
from qiskit.circuit import QuantumCircuit
(body,) = parameters
if not isinstance(body, QuantumCircuit):
raise CircuitError(
"WhileLoopOp expects a body parameter of type "
f"QuantumCircuit, but received {type(body)}."
)
if body.num_qubits != self.num_qubits or body.num_clbits != self.num_clbits:
raise CircuitError(
"Attempted to assign a body parameter with a num_qubits or "
"num_clbits different than that of the WhileLoopOp. "
f"WhileLoopOp num_qubits/clbits: {self.num_qubits}/{self.num_clbits} "
f"Supplied body num_qubits/clbits: {body.num_qubits}/{body.num_clbits}."
)
self._params = [body]
@property
def blocks(self):
return (self._params[0],)
def replace_blocks(self, blocks):
(body,) = blocks
return WhileLoopOp(self.condition, body, label=self.label)
def c_if(self, classical, val):
raise NotImplementedError(
"WhileLoopOp cannot be classically controlled through Instruction.c_if. "
"Please use an IfElseOp instead."
)
class WhileLoopContext:
"""A context manager for building up while loops onto circuits in a natural order, without
having to construct the loop body first.
Within the block, a lot of the bookkeeping is done for you; you do not need to keep track of
which qubits and clbits you are using, for example. All normal methods of accessing the qubits
on the underlying :obj:`~QuantumCircuit` will work correctly, and resolve into correct accesses
within the interior block.
You generally should never need to instantiate this object directly. Instead, use
:obj:`.QuantumCircuit.while_loop` in its context-manager form, i.e. by not supplying a ``body``
or sets of qubits and clbits.
Example usage::
from qiskit.circuit import QuantumCircuit, Clbit, Qubit
bits = [Qubit(), Qubit(), Clbit()]
qc = QuantumCircuit(bits)
with qc.while_loop((bits[2], 0)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
.. warning::
This is an internal interface and no part of it should be relied upon outside of Qiskit
Terra.
"""
__slots__ = ("_circuit", "_condition", "_label")
def __init__(
self,
circuit: QuantumCircuit,
condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | expr.Expr,
*,
label: str | None = None,
):
self._circuit = circuit
self._condition = validate_condition(condition)
self._label = label
def __enter__(self):
resources = condition_resources(self._condition)
self._circuit._push_scope(clbits=resources.clbits, registers=resources.cregs)
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
# If we're leaving the context manager because an exception was raised, there's nothing
# to do except restore the circuit state.
self._circuit._pop_scope()
return False
scope = self._circuit._pop_scope()
# Loops do not need to pass any further resources in, because this scope itself defines the
# extent of ``break`` and ``continue`` statements.
body = scope.build(scope.qubits(), scope.clbits())
self._circuit.append(
WhileLoopOp(self._condition, body, label=self._label),
body.qubits,
body.clbits,
)
return False