|
34 | 34 | import math |
35 | 35 | from copy import deepcopy |
36 | 36 |
|
| 37 | +import numpy as np |
| 38 | + |
37 | 39 | from projectq.types import BasicQubit |
38 | 40 | from ._command import Command, apply_command |
39 | 41 |
|
40 | 42 |
|
41 | 43 | ANGLE_PRECISION = 12 |
42 | 44 | ANGLE_TOLERANCE = 10 ** -ANGLE_PRECISION |
| 45 | +RTOL = 1e-10 |
| 46 | +ATOL = 1e-12 |
43 | 47 |
|
44 | 48 |
|
45 | 49 | class NotMergeable(Exception): |
@@ -200,8 +204,39 @@ def __or__(self, qubits): |
200 | 204 | apply_command(cmd) |
201 | 205 |
|
202 | 206 | def __eq__(self, other): |
203 | | - """ Return True if equal (i.e., instance of same class). """ |
204 | | - return isinstance(other, self.__class__) |
| 207 | + """ Return True if equal (i.e., instance of same class). |
| 208 | +
|
| 209 | + Unless both have a matrix attribute in which case we also check |
| 210 | + that the matrices are identical as people might want to do the |
| 211 | + following: |
| 212 | +
|
| 213 | + Example: |
| 214 | + .. code-block:: python |
| 215 | +
|
| 216 | + gate = BasicGate() |
| 217 | + gate.matrix = numpy.matrix([[1,0],[0, -1]]) |
| 218 | + """ |
| 219 | + if hasattr(self, 'matrix'): |
| 220 | + if not hasattr(other, 'matrix'): |
| 221 | + return False |
| 222 | + if hasattr(other, 'matrix'): |
| 223 | + if not hasattr(self, 'matrix'): |
| 224 | + return False |
| 225 | + if hasattr(self, 'matrix') and hasattr(other, 'matrix'): |
| 226 | + if (not isinstance(self.matrix, np.matrix) or |
| 227 | + not isinstance(other.matrix, np.matrix)): |
| 228 | + raise TypeError("One of the gates doesn't have the correct " |
| 229 | + "type (numpy.matrix) for the matrix " |
| 230 | + "attribute.") |
| 231 | + if (self.matrix.shape == other.matrix.shape and |
| 232 | + np.allclose(self.matrix, other.matrix, |
| 233 | + rtol=RTOL, atol=ATOL, |
| 234 | + equal_nan=False)): |
| 235 | + return True |
| 236 | + else: |
| 237 | + return False |
| 238 | + else: |
| 239 | + return isinstance(other, self.__class__) |
205 | 240 |
|
206 | 241 | def __ne__(self, other): |
207 | 242 | return not self.__eq__(other) |
|
0 commit comments