qft.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """An implementation of qubits and gates acting on them.
  2. Todo:
  3. * Update docstrings.
  4. * Update tests.
  5. * Implement apply using decompose.
  6. * Implement represent using decompose or something smarter. For this to
  7. work we first have to implement represent for SWAP.
  8. * Decide if we want upper index to be inclusive in the constructor.
  9. * Fix the printing of Rk gates in plotting.
  10. """
  11. from sympy.core.expr import Expr
  12. from sympy.core.numbers import (I, Integer, pi)
  13. from sympy.core.symbol import Symbol
  14. from sympy.functions.elementary.exponential import exp
  15. from sympy.matrices.dense import Matrix
  16. from sympy.functions import sqrt
  17. from sympy.physics.quantum.qapply import qapply
  18. from sympy.physics.quantum.qexpr import QuantumError, QExpr
  19. from sympy.matrices import eye
  20. from sympy.physics.quantum.tensorproduct import matrix_tensor_product
  21. from sympy.physics.quantum.gate import (
  22. Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate
  23. )
  24. __all__ = [
  25. 'QFT',
  26. 'IQFT',
  27. 'RkGate',
  28. 'Rk'
  29. ]
  30. #-----------------------------------------------------------------------------
  31. # Fourier stuff
  32. #-----------------------------------------------------------------------------
  33. class RkGate(OneQubitGate):
  34. """This is the R_k gate of the QTF."""
  35. gate_name = 'Rk'
  36. gate_name_latex = 'R'
  37. def __new__(cls, *args):
  38. if len(args) != 2:
  39. raise QuantumError(
  40. 'Rk gates only take two arguments, got: %r' % args
  41. )
  42. # For small k, Rk gates simplify to other gates, using these
  43. # substitutions give us familiar results for the QFT for small numbers
  44. # of qubits.
  45. target = args[0]
  46. k = args[1]
  47. if k == 1:
  48. return ZGate(target)
  49. elif k == 2:
  50. return PhaseGate(target)
  51. elif k == 3:
  52. return TGate(target)
  53. args = cls._eval_args(args)
  54. inst = Expr.__new__(cls, *args)
  55. inst.hilbert_space = cls._eval_hilbert_space(args)
  56. return inst
  57. @classmethod
  58. def _eval_args(cls, args):
  59. # Fall back to this, because Gate._eval_args assumes that args is
  60. # all targets and can't contain duplicates.
  61. return QExpr._eval_args(args)
  62. @property
  63. def k(self):
  64. return self.label[1]
  65. @property
  66. def targets(self):
  67. return self.label[:1]
  68. @property
  69. def gate_name_plot(self):
  70. return r'$%s_%s$' % (self.gate_name_latex, str(self.k))
  71. def get_target_matrix(self, format='sympy'):
  72. if format == 'sympy':
  73. return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]])
  74. raise NotImplementedError(
  75. 'Invalid format for the R_k gate: %r' % format)
  76. Rk = RkGate
  77. class Fourier(Gate):
  78. """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
  79. @classmethod
  80. def _eval_args(self, args):
  81. if len(args) != 2:
  82. raise QuantumError(
  83. 'QFT/IQFT only takes two arguments, got: %r' % args
  84. )
  85. if args[0] >= args[1]:
  86. raise QuantumError("Start must be smaller than finish")
  87. return Gate._eval_args(args)
  88. def _represent_default_basis(self, **options):
  89. return self._represent_ZGate(None, **options)
  90. def _represent_ZGate(self, basis, **options):
  91. """
  92. Represents the (I)QFT In the Z Basis
  93. """
  94. nqubits = options.get('nqubits', 0)
  95. if nqubits == 0:
  96. raise QuantumError(
  97. 'The number of qubits must be given as nqubits.')
  98. if nqubits < self.min_qubits:
  99. raise QuantumError(
  100. 'The number of qubits %r is too small for the gate.' % nqubits
  101. )
  102. size = self.size
  103. omega = self.omega
  104. #Make a matrix that has the basic Fourier Transform Matrix
  105. arrayFT = [[omega**(
  106. i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
  107. matrixFT = Matrix(arrayFT)
  108. #Embed the FT Matrix in a higher space, if necessary
  109. if self.label[0] != 0:
  110. matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
  111. if self.min_qubits < nqubits:
  112. matrixFT = matrix_tensor_product(
  113. matrixFT, eye(2**(nqubits - self.min_qubits)))
  114. return matrixFT
  115. @property
  116. def targets(self):
  117. return range(self.label[0], self.label[1])
  118. @property
  119. def min_qubits(self):
  120. return self.label[1]
  121. @property
  122. def size(self):
  123. """Size is the size of the QFT matrix"""
  124. return 2**(self.label[1] - self.label[0])
  125. @property
  126. def omega(self):
  127. return Symbol('omega')
  128. class QFT(Fourier):
  129. """The forward quantum Fourier transform."""
  130. gate_name = 'QFT'
  131. gate_name_latex = 'QFT'
  132. def decompose(self):
  133. """Decomposes QFT into elementary gates."""
  134. start = self.label[0]
  135. finish = self.label[1]
  136. circuit = 1
  137. for level in reversed(range(start, finish)):
  138. circuit = HadamardGate(level)*circuit
  139. for i in range(level - start):
  140. circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit
  141. for i in range((finish - start)//2):
  142. circuit = SwapGate(i + start, finish - i - 1)*circuit
  143. return circuit
  144. def _apply_operator_Qubit(self, qubits, **options):
  145. return qapply(self.decompose()*qubits)
  146. def _eval_inverse(self):
  147. return IQFT(*self.args)
  148. @property
  149. def omega(self):
  150. return exp(2*pi*I/self.size)
  151. class IQFT(Fourier):
  152. """The inverse quantum Fourier transform."""
  153. gate_name = 'IQFT'
  154. gate_name_latex = '{QFT^{-1}}'
  155. def decompose(self):
  156. """Decomposes IQFT into elementary gates."""
  157. start = self.args[0]
  158. finish = self.args[1]
  159. circuit = 1
  160. for i in range((finish - start)//2):
  161. circuit = SwapGate(i + start, finish - i - 1)*circuit
  162. for level in range(start, finish):
  163. for i in reversed(range(level - start)):
  164. circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit
  165. circuit = HadamardGate(level)*circuit
  166. return circuit
  167. def _eval_inverse(self):
  168. return QFT(*self.args)
  169. @property
  170. def omega(self):
  171. return exp(-2*pi*I/self.size)