-
Notifications
You must be signed in to change notification settings - Fork 269
/
_basics.py
executable file
·425 lines (320 loc) · 12.8 KB
/
_basics.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Defines the BasicGate class, the base class of all gates, the
BasicRotationGate class, the SelfInverseGate, the FastForwardingGate, the
ClassicalInstruction gate, and the BasicMathGate class.
Gates overload the | operator to allow the following syntax:
.. code-block:: python
Gate | (qreg1, qreg2, qreg2)
Gate | (qreg, qubit)
Gate | qreg
Gate | qubit
Gate | (qubit,)
This means that for more than one quantum argument (right side of | ), a tuple
needs to be made explicitely, while for one argument it is optional.
"""
import math
from copy import deepcopy
from projectq.types import BasicQubit
from ._command import Command, apply_command
class NotMergeable(Exception):
"""
Exception thrown when trying to merge two gates which are not mergeable (or
where it is not implemented (yet)).
"""
pass
class NotInvertible(Exception):
"""
Exception thrown when trying to invert a gate which is not invertable (or
where the inverse is not implemented (yet)).
"""
pass
class BasicGate(object):
"""
Base class of all gates.
"""
def __init__(self):
"""
Initialize a basic gate.
Note:
Set interchangeable qubit indices!
(gate.interchangeable_qubit_indices)
As an example, consider
.. code-block:: python
ExampleGate | (a,b,c,d,e)
where a and b are interchangeable. Then, call this function as
follows:
.. code-block:: python
self.set_interchangeable_qubit_indices([[0,1]])
As another example, consider
.. code-block:: python
ExampleGate2 | (a,b,c,d,e)
where a and b are interchangeable and, in addition, c, d, and e
are interchangeable among themselves. Then, call this function as
.. code-block:: python
self.set_interchangeable_qubit_indices([[0,1],[2,3,4]])
"""
self.interchangeable_qubit_indices = []
def get_inverse(self):
"""
Return the inverse gate.
Standard implementation of get_inverse:
Raises:
NotInvertible: inverse is not implemented
"""
raise NotInvertible("BasicGate: No get_inverse() implemented.")
def get_merged(self, other):
"""
Return this gate merged with another gate.
Standard implementation of get_merged:
Raises:
NotMergeable: merging is not implemented
"""
raise NotMergeable("BasicGate: No get_merged() implemented.")
@staticmethod
def make_tuple_of_qureg(qubits):
"""
Convert quantum input of "gate | quantum input" to internal formatting.
A Command object only accepts tuples of Quregs (list of Qubit objects)
as qubits input parameter. However, with this function we allow the
user to use a more flexible syntax:
1) Gate | qubit
2) Gate | [qubit0, qubit1]
3) Gate | qureg
4) Gate | (qubit, )
5) Gate | (qureg, qubit)
where qubit is a Qubit object and qureg is a Qureg object. This
function takes the right hand side of | and transforms it to the
correct input parameter of a Command object which is:
1) -> Gate | ([qubit], )
2) -> Gate | ([qubit0, qubit1], )
3) -> Gate | (qureg, )
4) -> Gate | ([qubit], )
5) -> Gate | (qureg, [qubit])
Args:
qubits: a Qubit object, a list of Qubit objects, a Qureg object,
or a tuple of Qubit or Qureg objects (can be mixed).
Returns:
Canonical representation (tuple<qureg>): A tuple containing Qureg
(or list of Qubits) objects.
"""
if not isinstance(qubits, tuple):
qubits = (qubits,)
qubits = list(qubits)
for i in range(len(qubits)):
if isinstance(qubits[i], BasicQubit):
qubits[i] = [qubits[i]]
return tuple(qubits)
def generate_command(self, qubits):
"""
Helper function to generate a command consisting of the gate and
the qubits being acted upon.
Args:
qubits: see BasicGate.make_tuple_of_qureg(qubits)
Returns:
A Command object containing the gate and the qubits.
"""
qubits = self.make_tuple_of_qureg(qubits)
engines = [q.engine for reg in qubits for q in reg]
eng = engines[0]
assert all(e is eng for e in engines)
return Command(eng, self, qubits)
def __or__(self, qubits):
""" Operator| overload which enables the syntax Gate | qubits.
Example:
1) Gate | qubit
2) Gate | [qubit0, qubit1]
3) Gate | qureg
4) Gate | (qubit, )
5) Gate | (qureg, qubit)
Args:
qubits: a Qubit object, a list of Qubit objects, a Qureg object, or
a tuple of Qubit or Qureg objects (can be mixed).
"""
cmd = self.generate_command(qubits)
apply_command(cmd)
def __eq__(self, other):
""" Return True if equal (i.e., instance of same class). """
return isinstance(other, self.__class__)
def __ne__(self, other):
return not self.__eq__(other)
class SelfInverseGate(BasicGate):
"""
Self-inverse basic gate class.
Automatic implementation of the get_inverse-member function for self-
inverse gates.
Example:
.. code-block:: python
# get_inverse(H) == H, it is a self-inverse gate:
get_inverse(H) | qubit
"""
def get_inverse(self):
return deepcopy(self)
class BasicRotationGate(BasicGate):
"""
Defines a base class of a rotation gate.
A rotation gate has a continuous parameter (the angle), labeled 'angle' /
self._angle. Its inverse is the same gate with the negated argument.
Rotation gates of the same class can be merged by adding the angles.
The continuous parameter is modulo 4 * pi, self._angle is in the interval
[0, 4 * pi).
"""
def __init__(self, angle):
"""
Initialize a basic rotation gate.
Args:
angle (float): Angle of rotation (saved modulo 4 * pi)
"""
BasicGate.__init__(self)
self._angle = float(angle) % (4. * math.pi)
def __str__(self):
"""
Return the string representation of a BasicRotationGate.
Returns the class name and the angle as
.. code-block:: python
[CLASSNAME]([ANGLE])
"""
return str(self.__class__.__name__) + "(" + str(self._angle) + ")"
def tex_str(self):
"""
Return the Latex string representation of a BasicRotationGate.
Returns the class name and the angle as a subscript, i.e.
.. code-block:: latex
[CLASSNAME]$_[ANGLE]$
"""
return str(self.__class__.__name__) + "$_{" + str(self._angle) + "}$"
def get_inverse(self):
"""
Return the inverse of this rotation gate (negate the angle, return new
object).
"""
if self._angle == 0:
return self.__class__(0)
else:
return self.__class__(-self._angle + 4 * math.pi)
def get_merged(self, other):
"""
Return self merged with another gate.
Default implementation handles rotation gate of the same type, where
angles are simply added.
Args:
other: Rotation gate of same type.
Raises:
NotMergeable: For non-rotation gates or rotation gates of
different type.
Returns:
New object representing the merged gates.
"""
if isinstance(other, self.__class__):
return self.__class__(self._angle + other._angle)
raise NotMergeable("Can't merge different types of rotation gates.")
def __eq__(self, other):
""" Return True if same class and same rotation angle. """
tolerance = 1.e-12
if isinstance(other, self.__class__):
difference = abs(self._angle - other._angle) % (4 * math.pi)
# Return True if angles are close to each other modulo 4 * pi
if difference < tolerance or difference > 4 * math.pi - tolerance:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
# Classical instruction gates never have control qubits.
class ClassicalInstructionGate(BasicGate):
"""
Classical instruction gate.
Base class for all gates which are not quantum gates in the typical sense,
e.g., measurement, allocation/deallocation, ...
"""
pass
class FastForwardingGate(ClassicalInstructionGate):
"""
Base class for classical instruction gates which require a fast-forward
through compiler engines that cache / buffer gates. Examples include
Measure and Deallocate, which both should be executed asap, such
that Measurement results are available and resources are freed,
respectively.
Note:
The only requirement is that FlushGate commands run the entire
circuit. FastForwardingGate objects can be used but the user cannot
expect a measurement result to be available for all back-ends when
calling only Measure. E.g., for the IBM Quantum Experience back-end,
sending the circuit for each Measure-gate would be too inefficient,
which is why a final
.. code-block: python
eng.flush()
is required before the circuit gets sent through the API.
"""
pass
class BasicMathGate(BasicGate):
"""
Base class for all math gates.
It allows efficient emulation by providing a mathematical representation
which is given by the concrete gate which derives from this base class.
The AddConstant gate, for example, registers a function of the form
.. code-block:: python
def add(x):
return (x+a,)
upon initialization. More generally, the function takes integers as
parameters and returns a tuple / list of outputs, each entry corresponding
to the function input. As an example, consider out-of-place
multiplication, which takes two input registers and adds the result into a
third, i.e., (a,b,c) -> (a,b,c+a*b). The corresponding function then is
.. code-block:: python
def multiply(a,b,c)
return (a,b,c+a*b)
"""
def __init__(self, math_fun):
"""
Initialize a BasicMathGate by providing the mathematical function that
it implements.
Args:
math_fun (function): Function which takes as many int values as
input, as the gate takes registers. For each of these values,
it then returns the output (i.e., it returns a list/tuple of
output values).
Example:
.. code-block:: python
def add(a,b):
return (a,a+b)
BasicMathGate.__init__(self, add)
If the gate acts on, e.g., fixed point numbers, the number of bits per
register is also required in order to describe the action of such a
mathematical gate. For this reason, there is
.. code-block:: python
BasicMathGate.get_math_function(qubits)
which can be overwritten by the gate deriving from BasicMathGate.
Example:
.. code-block:: python
def get_math_function(self, qubits):
n = len(qubits[0])
scal = 2.**n
def math_fun(a):
return (int(scal * (math.sin(math.pi * a / scal))),)
return math_fun
"""
BasicGate.__init__(self)
math_function = lambda x: list(math_fun(*x))
self._math_function = math_function
def get_math_function(self, qubits):
"""
Return the math function which corresponds to the action of this math
gate, given the input to the gate (a tuple of quantum registers).
Args:
qubits (tuple<Qureg>): Qubits to which the math gate is being
applied.
Returns:
math_fun (function): Python function describing the action of this
gate. (See BasicMathGate.__init__ for an example).
"""
return self._math_function