-
Notifications
You must be signed in to change notification settings - Fork 289
Expand file tree
/
Copy path_basics.py
More file actions
executable file
·677 lines (499 loc) · 21.1 KB
/
_basics.py
File metadata and controls
executable file
·677 lines (499 loc) · 21.1 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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.
"""
Definitions of some of the most basic quantum gates.
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 | (qureg1, qureg2, qureg2)
Gate | (qureg, qubit)
Gate | qureg
Gate | qubit
Gate | (qubit,)
This means that for more than one quantum argument (right side of | ), a tuple needs to be made explicitly, while for
one argument it is optional.
"""
import math
import unicodedata
from copy import deepcopy
import numpy as np
from projectq.types import BasicQubit
from ._command import Command, Commutability, apply_command
ANGLE_PRECISION = 12
ANGLE_TOLERANCE = 10**-ANGLE_PRECISION
RTOL = 1e-10
ATOL = 1e-12
class NotMergeable(Exception):
"""
Exception thrown when trying to merge two gates which are not mergeable.
This exception is also thrown if the merging is not implemented (yet)).
"""
class NotInvertible(Exception):
"""
Exception thrown when trying to invert a gate which is not invertable.
This exception is also thrown if the inverse is not implemented (yet).
"""
class BasicGateMeta(type):
"""
Meta class for all gates; mainly used to ensure that all gate classes have some basic class variable defined.
"""
def __new__(cls, name, bases, attrs):
def get_commutable_gates(self):
return self._commutable_gates
return super().__new__(
cls, name, bases, {**attrs, get_commutable_gates.__name__: get_commutable_gates, '_commutable_gates': set()}
)
class BasicGate(metaclass=BasicGateMeta):
"""
A list of gates that commute with this gate class
"""
"""
Base class of all gates. (Don't use it directly but derive from it)
"""
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.")
def get_commutable_gates(self):
return []
def get_commutable_circuit_list(self, n=0):
"""
Args:
n (int): The CNOT gate needs to be able to pass in parameter n in
this method.
Returns:
_commutable_circuit_list (list): the list of commutable circuits
associated with this gate.
"""
return []
@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, qubit in enumerate(qubits):
if isinstance(qubit, BasicQubit):
qubits[i] = [qubit]
return tuple(qubits)
def generate_command(self, qubits):
"""
Generate a command.
The command object created consists 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]
if not all(e is eng for e in engines):
raise ValueError('All qubits must belong to the same engine!')
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):
"""
Equal operator.
Return True if instance of the same class, unless other is an instance of :class:MatrixGate, in which case
equality is to be checked by testing for existence and (approximate) equality of matrix representations.
"""
if isinstance(other, self.__class__):
return True
if isinstance(other, MatrixGate):
return NotImplemented
return False
def __str__(self):
"""Return a string representation of the object."""
raise NotImplementedError('This gate does not implement __str__.')
def to_string(self, symbols): # pylint: disable=unused-argument
"""
Return a string representation of the object.
Achieve same function as str() but can be extended for configurable representation
"""
return str(self)
def __hash__(self):
"""Compute the hash of the object."""
return hash(str(self))
def is_identity(self):
"""Return True if the gate is an identity gate. In this base class, always returns False."""
return False
def is_commutable(self, other):
"""Determine whether this gate is commutable with
another gate.
Args:
other (Gate): The other gate.
Returns:
commutability (Commutability) : An enum which
indicates whether the next gate is commutable,
not commutable or maybe commutable.
"""
for gate in self.get_commutable_gates():
if type(other) is gate:
return Commutability.COMMUTABLE
else:
return Commutability.NOT_COMMUTABLE
class MatrixGate(BasicGate):
"""
A gate class whose instances are defined by a matrix.
Note:
Use this gate class only for gates acting on a small numbers of qubits. In general, consider instead using
one of the provided ProjectQ gates or define a new class as this allows the compiler to work symbolically.
Example:
.. code-block:: python
gate = MatrixGate([[0, 1], [1, 0]])
gate | qubit
"""
def __init__(self, matrix=None):
"""
Initialize a MatrixGate object.
Args:
matrix(numpy.matrix): matrix which defines the gate. Default: None
"""
super().__init__()
self._matrix = np.matrix(matrix) if matrix is not None else None
@property
def matrix(self):
"""Access to the matrix property of this gate."""
return self._matrix
@matrix.setter
def matrix(self, matrix):
"""Set the matrix property of this gate."""
self._matrix = np.matrix(matrix)
def __eq__(self, other):
"""
Equal operator.
Return True only if both gates have a matrix representation and the matrices are (approximately)
equal. Otherwise return False.
"""
if not hasattr(other, 'matrix'):
return False
if not isinstance(self.matrix, np.matrix) or not isinstance(other.matrix, np.matrix):
raise TypeError("One of the gates doesn't have the correct type (numpy.matrix) for the matrix attribute.")
if self.matrix.shape == other.matrix.shape and np.allclose(
self.matrix, other.matrix, rtol=RTOL, atol=ATOL, equal_nan=False
):
return True
return False
def __str__(self):
"""Return a string representation of the object."""
return f"MatrixGate({str(self.matrix.tolist())})"
def __hash__(self):
"""Compute the hash of the object."""
return hash(str(self))
def get_inverse(self):
"""Return the inverse of this gate."""
return MatrixGate(np.linalg.inv(self.matrix))
class SelfInverseGate(BasicGate): # pylint: disable=abstract-method
"""
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 the inverse of this gate."""
return deepcopy(self)
class BasicRotationGate(BasicGate):
"""
Base class of for all rotation gates.
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)
"""
super().__init__()
rounded_angle = round(float(angle) % (4.0 * math.pi), ANGLE_PRECISION)
if rounded_angle > 4 * math.pi - ANGLE_TOLERANCE:
rounded_angle = 0.0
self.angle = rounded_angle
def __str__(self):
"""
Return the string representation of a BasicRotationGate.
Returns the class name and the angle as
.. code-block:: python
[CLASSNAME]([ANGLE])
"""
return self.to_string()
def to_string(self, symbols=False):
"""
Return the string representation of a BasicRotationGate.
Args:
symbols (bool): uses the pi character and round the angle for a more user friendly display if True, full
angle written in radian otherwise.
"""
if symbols:
angle = f"({str(round(self.angle / math.pi, 3))}{unicodedata.lookup('GREEK SMALL LETTER PI')})"
else:
angle = f"({str(self.angle)})"
return str(self.__class__.__name__) + 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 f"{str(self.__class__.__name__)}$_{{{str(round(self.angle / math.pi, 3))}\\pi}}$"
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)
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."""
if isinstance(other, self.__class__):
return self.angle == other.angle
return False
def __hash__(self):
"""Compute the hash of the object."""
return hash(str(self))
def is_identity(self):
"""Return True if the gate is equivalent to an Identity gate."""
return self.angle in (0.0, 4 * math.pi)
class BasicPhaseGate(BasicGate):
"""
Base class for all phase gates.
A phase gate has a continuous parameter (the angle), labeled 'angle' / self.angle. Its inverse is the same gate
with the negated argument. Phase gates of the same class can be merged by adding the angles. The continuous
parameter is modulo 2 * pi, self.angle is in the interval [0, 2 * pi).
"""
def __init__(self, angle):
"""
Initialize a basic rotation gate.
Args:
angle (float): Angle of rotation (saved modulo 2 * pi)
"""
super().__init__()
rounded_angle = round(float(angle) % (2.0 * math.pi), ANGLE_PRECISION)
if rounded_angle > 2 * math.pi - ANGLE_TOLERANCE:
rounded_angle = 0.0
self.angle = rounded_angle
def __str__(self):
"""
Return the string representation of a BasicPhaseGate.
Returns the class name and the angle as
.. code-block:: python
[CLASSNAME]([ANGLE])
"""
return f"{str(self.__class__.__name__)}({str(self.angle)})"
def tex_str(self):
"""
Return the Latex string representation of a BasicPhaseGate.
Returns the class name and the angle as a subscript, i.e.
.. code-block:: latex
[CLASSNAME]$_[ANGLE]$
"""
return f"{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)
return self.__class__(-self.angle + 2 * 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."""
if isinstance(other, self.__class__):
return self.angle == other.angle
return False
def __hash__(self):
"""Compute the hash of the object."""
return hash(str(self))
# Classical instruction gates never have control qubits.
class ClassicalInstructionGate(BasicGate): # pylint: disable=abstract-method
"""
Classical instruction gate.
Base class for all gates which are not quantum gates in the typical sense, e.g., measurement,
allocation/deallocation, ...
"""
class FastForwardingGate(ClassicalInstructionGate): # pylint: disable=abstract-method
"""
Base class for fast-forward gates.
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.
"""
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)
super().__init__(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.0**n
def math_fun(a):
return (int(scal * (math.sin(math.pi * a / scal))),)
return math_fun
"""
super().__init__()
def math_function(arg):
return list(math_fun(*arg))
self._math_function = math_function
def __str__(self):
"""Return a string representation of the object."""
return "MATH"
def get_math_function(self, qubits): # pylint: disable=unused-argument
"""
Get the math function associated with a BasicMathGate.
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