tensorproduct.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """Abstract tensor product."""
  2. from sympy.core.add import Add
  3. from sympy.core.expr import Expr
  4. from sympy.core.mul import Mul
  5. from sympy.core.power import Pow
  6. from sympy.core.sympify import sympify
  7. from sympy.matrices.dense import MutableDenseMatrix as Matrix
  8. from sympy.printing.pretty.stringpict import prettyForm
  9. from sympy.physics.quantum.qexpr import QuantumError
  10. from sympy.physics.quantum.dagger import Dagger
  11. from sympy.physics.quantum.commutator import Commutator
  12. from sympy.physics.quantum.anticommutator import AntiCommutator
  13. from sympy.physics.quantum.state import Ket, Bra
  14. from sympy.physics.quantum.matrixutils import (
  15. numpy_ndarray,
  16. scipy_sparse_matrix,
  17. matrix_tensor_product
  18. )
  19. from sympy.physics.quantum.trace import Tr
  20. __all__ = [
  21. 'TensorProduct',
  22. 'tensor_product_simp'
  23. ]
  24. #-----------------------------------------------------------------------------
  25. # Tensor product
  26. #-----------------------------------------------------------------------------
  27. _combined_printing = False
  28. def combined_tensor_printing(combined):
  29. """Set flag controlling whether tensor products of states should be
  30. printed as a combined bra/ket or as an explicit tensor product of different
  31. bra/kets. This is a global setting for all TensorProduct class instances.
  32. Parameters
  33. ----------
  34. combine : bool
  35. When true, tensor product states are combined into one ket/bra, and
  36. when false explicit tensor product notation is used between each
  37. ket/bra.
  38. """
  39. global _combined_printing
  40. _combined_printing = combined
  41. class TensorProduct(Expr):
  42. """The tensor product of two or more arguments.
  43. For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
  44. or tensor product matrix. For other objects a symbolic ``TensorProduct``
  45. instance is returned. The tensor product is a non-commutative
  46. multiplication that is used primarily with operators and states in quantum
  47. mechanics.
  48. Currently, the tensor product distinguishes between commutative and
  49. non-commutative arguments. Commutative arguments are assumed to be scalars
  50. and are pulled out in front of the ``TensorProduct``. Non-commutative
  51. arguments remain in the resulting ``TensorProduct``.
  52. Parameters
  53. ==========
  54. args : tuple
  55. A sequence of the objects to take the tensor product of.
  56. Examples
  57. ========
  58. Start with a simple tensor product of SymPy matrices::
  59. >>> from sympy import Matrix
  60. >>> from sympy.physics.quantum import TensorProduct
  61. >>> m1 = Matrix([[1,2],[3,4]])
  62. >>> m2 = Matrix([[1,0],[0,1]])
  63. >>> TensorProduct(m1, m2)
  64. Matrix([
  65. [1, 0, 2, 0],
  66. [0, 1, 0, 2],
  67. [3, 0, 4, 0],
  68. [0, 3, 0, 4]])
  69. >>> TensorProduct(m2, m1)
  70. Matrix([
  71. [1, 2, 0, 0],
  72. [3, 4, 0, 0],
  73. [0, 0, 1, 2],
  74. [0, 0, 3, 4]])
  75. We can also construct tensor products of non-commutative symbols:
  76. >>> from sympy import Symbol
  77. >>> A = Symbol('A',commutative=False)
  78. >>> B = Symbol('B',commutative=False)
  79. >>> tp = TensorProduct(A, B)
  80. >>> tp
  81. AxB
  82. We can take the dagger of a tensor product (note the order does NOT reverse
  83. like the dagger of a normal product):
  84. >>> from sympy.physics.quantum import Dagger
  85. >>> Dagger(tp)
  86. Dagger(A)xDagger(B)
  87. Expand can be used to distribute a tensor product across addition:
  88. >>> C = Symbol('C',commutative=False)
  89. >>> tp = TensorProduct(A+B,C)
  90. >>> tp
  91. (A + B)xC
  92. >>> tp.expand(tensorproduct=True)
  93. AxC + BxC
  94. """
  95. is_commutative = False
  96. def __new__(cls, *args):
  97. if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):
  98. return matrix_tensor_product(*args)
  99. c_part, new_args = cls.flatten(sympify(args))
  100. c_part = Mul(*c_part)
  101. if len(new_args) == 0:
  102. return c_part
  103. elif len(new_args) == 1:
  104. return c_part * new_args[0]
  105. else:
  106. tp = Expr.__new__(cls, *new_args)
  107. return c_part * tp
  108. @classmethod
  109. def flatten(cls, args):
  110. # TODO: disallow nested TensorProducts.
  111. c_part = []
  112. nc_parts = []
  113. for arg in args:
  114. cp, ncp = arg.args_cnc()
  115. c_part.extend(list(cp))
  116. nc_parts.append(Mul._from_args(ncp))
  117. return c_part, nc_parts
  118. def _eval_adjoint(self):
  119. return TensorProduct(*[Dagger(i) for i in self.args])
  120. def _eval_rewrite(self, rule, args, **hints):
  121. return TensorProduct(*args).expand(tensorproduct=True)
  122. def _sympystr(self, printer, *args):
  123. length = len(self.args)
  124. s = ''
  125. for i in range(length):
  126. if isinstance(self.args[i], (Add, Pow, Mul)):
  127. s = s + '('
  128. s = s + printer._print(self.args[i])
  129. if isinstance(self.args[i], (Add, Pow, Mul)):
  130. s = s + ')'
  131. if i != length - 1:
  132. s = s + 'x'
  133. return s
  134. def _pretty(self, printer, *args):
  135. if (_combined_printing and
  136. (all(isinstance(arg, Ket) for arg in self.args) or
  137. all(isinstance(arg, Bra) for arg in self.args))):
  138. length = len(self.args)
  139. pform = printer._print('', *args)
  140. for i in range(length):
  141. next_pform = printer._print('', *args)
  142. length_i = len(self.args[i].args)
  143. for j in range(length_i):
  144. part_pform = printer._print(self.args[i].args[j], *args)
  145. next_pform = prettyForm(*next_pform.right(part_pform))
  146. if j != length_i - 1:
  147. next_pform = prettyForm(*next_pform.right(', '))
  148. if len(self.args[i].args) > 1:
  149. next_pform = prettyForm(
  150. *next_pform.parens(left='{', right='}'))
  151. pform = prettyForm(*pform.right(next_pform))
  152. if i != length - 1:
  153. pform = prettyForm(*pform.right(',' + ' '))
  154. pform = prettyForm(*pform.left(self.args[0].lbracket))
  155. pform = prettyForm(*pform.right(self.args[0].rbracket))
  156. return pform
  157. length = len(self.args)
  158. pform = printer._print('', *args)
  159. for i in range(length):
  160. next_pform = printer._print(self.args[i], *args)
  161. if isinstance(self.args[i], (Add, Mul)):
  162. next_pform = prettyForm(
  163. *next_pform.parens(left='(', right=')')
  164. )
  165. pform = prettyForm(*pform.right(next_pform))
  166. if i != length - 1:
  167. if printer._use_unicode:
  168. pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
  169. else:
  170. pform = prettyForm(*pform.right('x' + ' '))
  171. return pform
  172. def _latex(self, printer, *args):
  173. if (_combined_printing and
  174. (all(isinstance(arg, Ket) for arg in self.args) or
  175. all(isinstance(arg, Bra) for arg in self.args))):
  176. def _label_wrap(label, nlabels):
  177. return label if nlabels == 1 else r"\left\{%s\right\}" % label
  178. s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
  179. len(arg.args)) for arg in self.args])
  180. return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
  181. self.args[0].rbracket_latex)
  182. length = len(self.args)
  183. s = ''
  184. for i in range(length):
  185. if isinstance(self.args[i], (Add, Mul)):
  186. s = s + '\\left('
  187. # The extra {} brackets are needed to get matplotlib's latex
  188. # rendered to render this properly.
  189. s = s + '{' + printer._print(self.args[i], *args) + '}'
  190. if isinstance(self.args[i], (Add, Mul)):
  191. s = s + '\\right)'
  192. if i != length - 1:
  193. s = s + '\\otimes '
  194. return s
  195. def doit(self, **hints):
  196. return TensorProduct(*[item.doit(**hints) for item in self.args])
  197. def _eval_expand_tensorproduct(self, **hints):
  198. """Distribute TensorProducts across addition."""
  199. args = self.args
  200. add_args = []
  201. for i in range(len(args)):
  202. if isinstance(args[i], Add):
  203. for aa in args[i].args:
  204. tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
  205. c_part, nc_part = tp.args_cnc()
  206. # Check for TensorProduct object: is the one object in nc_part, if any:
  207. # (Note: any other object type to be expanded must be added here)
  208. if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct):
  209. nc_part = (nc_part[0]._eval_expand_tensorproduct(), )
  210. add_args.append(Mul(*c_part)*Mul(*nc_part))
  211. break
  212. if add_args:
  213. return Add(*add_args)
  214. else:
  215. return self
  216. def _eval_trace(self, **kwargs):
  217. indices = kwargs.get('indices', None)
  218. exp = tensor_product_simp(self)
  219. if indices is None or len(indices) == 0:
  220. return Mul(*[Tr(arg).doit() for arg in exp.args])
  221. else:
  222. return Mul(*[Tr(value).doit() if idx in indices else value
  223. for idx, value in enumerate(exp.args)])
  224. def tensor_product_simp_Mul(e):
  225. """Simplify a Mul with TensorProducts.
  226. Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
  227. to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
  228. simple cases where the initial ``Mul`` only has scalars and raw
  229. ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
  230. ``TensorProduct``s.
  231. Parameters
  232. ==========
  233. e : Expr
  234. A ``Mul`` of ``TensorProduct``s to be simplified.
  235. Returns
  236. =======
  237. e : Expr
  238. A ``TensorProduct`` of ``Mul``s.
  239. Examples
  240. ========
  241. This is an example of the type of simplification that this function
  242. performs::
  243. >>> from sympy.physics.quantum.tensorproduct import \
  244. tensor_product_simp_Mul, TensorProduct
  245. >>> from sympy import Symbol
  246. >>> A = Symbol('A',commutative=False)
  247. >>> B = Symbol('B',commutative=False)
  248. >>> C = Symbol('C',commutative=False)
  249. >>> D = Symbol('D',commutative=False)
  250. >>> e = TensorProduct(A,B)*TensorProduct(C,D)
  251. >>> e
  252. AxB*CxD
  253. >>> tensor_product_simp_Mul(e)
  254. (A*C)x(B*D)
  255. """
  256. # TODO: This won't work with Muls that have other composites of
  257. # TensorProducts, like an Add, Commutator, etc.
  258. # TODO: This only works for the equivalent of single Qbit gates.
  259. if not isinstance(e, Mul):
  260. return e
  261. c_part, nc_part = e.args_cnc()
  262. n_nc = len(nc_part)
  263. if n_nc == 0:
  264. return e
  265. elif n_nc == 1:
  266. if isinstance(nc_part[0], Pow):
  267. return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])
  268. return e
  269. elif e.has(TensorProduct):
  270. current = nc_part[0]
  271. if not isinstance(current, TensorProduct):
  272. if isinstance(current, Pow):
  273. if isinstance(current.base, TensorProduct):
  274. current = tensor_product_simp_Pow(current)
  275. else:
  276. raise TypeError('TensorProduct expected, got: %r' % current)
  277. n_terms = len(current.args)
  278. new_args = list(current.args)
  279. for next in nc_part[1:]:
  280. # TODO: check the hilbert spaces of next and current here.
  281. if isinstance(next, TensorProduct):
  282. if n_terms != len(next.args):
  283. raise QuantumError(
  284. 'TensorProducts of different lengths: %r and %r' %
  285. (current, next)
  286. )
  287. for i in range(len(new_args)):
  288. new_args[i] = new_args[i] * next.args[i]
  289. else:
  290. if isinstance(next, Pow):
  291. if isinstance(next.base, TensorProduct):
  292. new_tp = tensor_product_simp_Pow(next)
  293. for i in range(len(new_args)):
  294. new_args[i] = new_args[i] * new_tp.args[i]
  295. else:
  296. raise TypeError('TensorProduct expected, got: %r' % next)
  297. else:
  298. raise TypeError('TensorProduct expected, got: %r' % next)
  299. current = next
  300. return Mul(*c_part) * TensorProduct(*new_args)
  301. elif e.has(Pow):
  302. new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]
  303. return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))
  304. else:
  305. return e
  306. def tensor_product_simp_Pow(e):
  307. """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""
  308. if not isinstance(e, Pow):
  309. return e
  310. if isinstance(e.base, TensorProduct):
  311. return TensorProduct(*[ b**e.exp for b in e.base.args])
  312. else:
  313. return e
  314. def tensor_product_simp(e, **hints):
  315. """Try to simplify and combine TensorProducts.
  316. In general this will try to pull expressions inside of ``TensorProducts``.
  317. It currently only works for relatively simple cases where the products have
  318. only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
  319. of ``TensorProducts``. It is best to see what it does by showing examples.
  320. Examples
  321. ========
  322. >>> from sympy.physics.quantum import tensor_product_simp
  323. >>> from sympy.physics.quantum import TensorProduct
  324. >>> from sympy import Symbol
  325. >>> A = Symbol('A',commutative=False)
  326. >>> B = Symbol('B',commutative=False)
  327. >>> C = Symbol('C',commutative=False)
  328. >>> D = Symbol('D',commutative=False)
  329. First see what happens to products of tensor products:
  330. >>> e = TensorProduct(A,B)*TensorProduct(C,D)
  331. >>> e
  332. AxB*CxD
  333. >>> tensor_product_simp(e)
  334. (A*C)x(B*D)
  335. This is the core logic of this function, and it works inside, powers, sums,
  336. commutators and anticommutators as well:
  337. >>> tensor_product_simp(e**2)
  338. (A*C)x(B*D)**2
  339. """
  340. if isinstance(e, Add):
  341. return Add(*[tensor_product_simp(arg) for arg in e.args])
  342. elif isinstance(e, Pow):
  343. if isinstance(e.base, TensorProduct):
  344. return tensor_product_simp_Pow(e)
  345. else:
  346. return tensor_product_simp(e.base) ** e.exp
  347. elif isinstance(e, Mul):
  348. return tensor_product_simp_Mul(e)
  349. elif isinstance(e, Commutator):
  350. return Commutator(*[tensor_product_simp(arg) for arg in e.args])
  351. elif isinstance(e, AntiCommutator):
  352. return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
  353. else:
  354. return e