forked from Qiskit/qiskit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcmt.py
256 lines (211 loc) · 10.1 KB
/
mcmt.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# 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.
"""Multiple-Control, Multiple-Target Gate."""
from __future__ import annotations
from collections.abc import Callable
from qiskit import circuit
from qiskit.circuit import ControlledGate, Gate, QuantumRegister, QuantumCircuit
from qiskit.exceptions import QiskitError
# pylint: disable=cyclic-import
from ..standard_gates import XGate, YGate, ZGate, HGate, TGate, TdgGate, SGate, SdgGate
class MCMT(QuantumCircuit):
"""The multi-controlled multi-target gate, for an arbitrary singly controlled target gate.
For example, the H gate controlled on 3 qubits and acting on 2 target qubit is represented as:
.. parsed-literal::
───■────
│
───■────
│
───■────
┌──┴───┐
┤0 ├
│ 2-H │
┤1 ├
└──────┘
This default implementations requires no ancilla qubits, by broadcasting the target gate
to the number of target qubits and using Qiskit's generic control routine to control the
broadcasted target on the control qubits. If ancilla qubits are available, a more efficient
variant using the so-called V-chain decomposition can be used. This is implemented in
:class:`~qiskit.circuit.library.MCMTVChain`.
"""
def __init__(
self,
gate: Gate | Callable[[QuantumCircuit, circuit.Qubit, circuit.Qubit], circuit.Instruction],
num_ctrl_qubits: int,
num_target_qubits: int,
) -> None:
"""Create a new multi-control multi-target gate.
Args:
gate: The gate to be applied controlled on the control qubits and applied to the target
qubits. Can be either a Gate or a circuit method.
If it is a callable, it will be casted to a Gate.
num_ctrl_qubits: The number of control qubits.
num_target_qubits: The number of target qubits.
Raises:
AttributeError: If the gate cannot be casted to a controlled gate.
AttributeError: If the number of controls or targets is 0.
"""
if num_ctrl_qubits == 0 or num_target_qubits == 0:
raise AttributeError("Need at least one control and one target qubit.")
# set the internal properties and determine the number of qubits
self.gate = self._identify_gate(gate)
self.num_ctrl_qubits = num_ctrl_qubits
self.num_target_qubits = num_target_qubits
num_qubits = num_ctrl_qubits + num_target_qubits + self.num_ancilla_qubits
# initialize the circuit object
super().__init__(num_qubits, name="mcmt")
self._label = f"{num_target_qubits}-{self.gate.name.capitalize()}"
# build the circuit
self._build()
def _build(self):
"""Define the MCMT gate without ancillas."""
if self.num_target_qubits == 1:
# no broadcasting needed (makes for better circuit diagrams)
broadcasted_gate = self.gate
else:
broadcasted = QuantumCircuit(self.num_target_qubits, name=self._label)
for target in list(range(self.num_target_qubits)):
broadcasted.append(self.gate, [target], [])
broadcasted_gate = broadcasted.to_gate()
mcmt_gate = broadcasted_gate.control(self.num_ctrl_qubits)
self.append(mcmt_gate, self.qubits, [])
@property
def num_ancilla_qubits(self):
"""Return the number of ancillas."""
return 0
def _identify_gate(self, gate):
"""Case the gate input to a gate."""
valid_gates = {
"ch": HGate(),
"cx": XGate(),
"cy": YGate(),
"cz": ZGate(),
"h": HGate(),
"s": SGate(),
"sdg": SdgGate(),
"x": XGate(),
"y": YGate(),
"z": ZGate(),
"t": TGate(),
"tdg": TdgGate(),
}
if isinstance(gate, ControlledGate):
base_gate = gate.base_gate
elif isinstance(gate, Gate):
if gate.num_qubits != 1:
raise AttributeError("Base gate must act on one qubit only.")
base_gate = gate
elif isinstance(gate, QuantumCircuit):
if gate.num_qubits != 1:
raise AttributeError(
"The circuit you specified as control gate can only have one qubit!"
)
base_gate = gate.to_gate() # raises error if circuit contains non-unitary instructions
else:
if callable(gate): # identify via name of the passed function
name = gate.__name__
elif isinstance(gate, str):
name = gate
else:
raise AttributeError(f"Invalid gate specified: {gate}")
base_gate = valid_gates[name]
return base_gate
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None, annotated=False):
"""Return the controlled version of the MCMT circuit."""
if not annotated and ctrl_state is None:
gate = MCMT(self.gate, self.num_ctrl_qubits + num_ctrl_qubits, self.num_target_qubits)
else:
gate = super().control(num_ctrl_qubits, label, ctrl_state, annotated=annotated)
return gate
def inverse(self):
"""Return the inverse MCMT circuit, which is itself."""
return MCMT(self.gate, self.num_ctrl_qubits, self.num_target_qubits)
class MCMTVChain(MCMT):
"""The MCMT implementation using the CCX V-chain.
This implementation requires ancillas but is decomposed into a much shallower circuit
than the default implementation in :class:`~qiskit.circuit.library.MCMT`.
**Expanded Circuit:**
.. plot::
from qiskit.circuit.library import MCMTVChain, ZGate
from qiskit.visualization.library import _generate_circuit_library_visualization
circuit = MCMTVChain(ZGate(), 2, 2)
_generate_circuit_library_visualization(circuit.decompose())
**Examples:**
>>> from qiskit.circuit.library import HGate
>>> MCMTVChain(HGate(), 3, 2).draw()
q_0: ──■────────────────────────■──
│ │
q_1: ──■────────────────────────■──
│ │
q_2: ──┼────■──────────────■────┼──
│ │ ┌───┐ │ │
q_3: ──┼────┼──┤ H ├───────┼────┼──
│ │ └─┬─┘┌───┐ │ │
q_4: ──┼────┼────┼──┤ H ├──┼────┼──
┌─┴─┐ │ │ └─┬─┘ │ ┌─┴─┐
q_5: ┤ X ├──■────┼────┼────■──┤ X ├
└───┘┌─┴─┐ │ │ ┌─┴─┐└───┘
q_6: ─────┤ X ├──■────■──┤ X ├─────
└───┘ └───┘
"""
def _build(self):
"""Define the MCMT gate."""
control_qubits = self.qubits[: self.num_ctrl_qubits]
target_qubits = self.qubits[
self.num_ctrl_qubits : self.num_ctrl_qubits + self.num_target_qubits
]
ancilla_qubits = self.qubits[self.num_ctrl_qubits + self.num_target_qubits :]
if len(ancilla_qubits) > 0:
master_control = ancilla_qubits[-1]
else:
master_control = control_qubits[0]
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=False)
for qubit in target_qubits:
self.append(self.gate.control(), [master_control, qubit], [])
self._ccx_v_chain_rule(control_qubits, ancilla_qubits, reverse=True)
@property
def num_ancilla_qubits(self):
"""Return the number of ancilla qubits required."""
return max(0, self.num_ctrl_qubits - 1)
def _ccx_v_chain_rule(
self,
control_qubits: QuantumRegister | list[circuit.Qubit],
ancilla_qubits: QuantumRegister | list[circuit.Qubit],
reverse: bool = False,
) -> None:
"""Get the rule for the CCX V-chain.
The CCX V-chain progressively computes the CCX of the control qubits and puts the final
result in the last ancillary qubit.
Args:
control_qubits: The control qubits.
ancilla_qubits: The ancilla qubits.
reverse: If True, compute the chain down to the qubit. If False, compute upwards.
Returns:
The rule for the (reversed) CCX V-chain.
Raises:
QiskitError: If an insufficient number of ancilla qubits was provided.
"""
if len(ancilla_qubits) == 0:
return
if len(ancilla_qubits) < len(control_qubits) - 1:
raise QiskitError("Insufficient number of ancilla qubits.")
iterations = list(enumerate(range(2, len(control_qubits))))
if not reverse:
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
for i, j in iterations:
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
else:
for i, j in reversed(iterations):
self.ccx(control_qubits[j], ancilla_qubits[i], ancilla_qubits[i + 1])
self.ccx(control_qubits[0], control_qubits[1], ancilla_qubits[0])
def inverse(self):
return MCMTVChain(self.gate, self.num_ctrl_qubits, self.num_target_qubits)