commutator.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """The commutator: [A,B] = A*B - B*A."""
  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.singleton import S
  7. from sympy.printing.pretty.stringpict import prettyForm
  8. from sympy.physics.quantum.dagger import Dagger
  9. from sympy.physics.quantum.operator import Operator
  10. __all__ = [
  11. 'Commutator'
  12. ]
  13. #-----------------------------------------------------------------------------
  14. # Commutator
  15. #-----------------------------------------------------------------------------
  16. class Commutator(Expr):
  17. """The standard commutator, in an unevaluated state.
  18. Explanation
  19. ===========
  20. Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
  21. class returns the commutator in an unevaluated form. To evaluate the
  22. commutator, use the ``.doit()`` method.
  23. Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
  24. arguments of the commutator are put into canonical order using ``__cmp__``.
  25. If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
  26. Parameters
  27. ==========
  28. A : Expr
  29. The first argument of the commutator [A,B].
  30. B : Expr
  31. The second argument of the commutator [A,B].
  32. Examples
  33. ========
  34. >>> from sympy.physics.quantum import Commutator, Dagger, Operator
  35. >>> from sympy.abc import x, y
  36. >>> A = Operator('A')
  37. >>> B = Operator('B')
  38. >>> C = Operator('C')
  39. Create a commutator and use ``.doit()`` to evaluate it:
  40. >>> comm = Commutator(A, B)
  41. >>> comm
  42. [A,B]
  43. >>> comm.doit()
  44. A*B - B*A
  45. The commutator orders it arguments in canonical order:
  46. >>> comm = Commutator(B, A); comm
  47. -[A,B]
  48. Commutative constants are factored out:
  49. >>> Commutator(3*x*A, x*y*B)
  50. 3*x**2*y*[A,B]
  51. Using ``.expand(commutator=True)``, the standard commutator expansion rules
  52. can be applied:
  53. >>> Commutator(A+B, C).expand(commutator=True)
  54. [A,C] + [B,C]
  55. >>> Commutator(A, B+C).expand(commutator=True)
  56. [A,B] + [A,C]
  57. >>> Commutator(A*B, C).expand(commutator=True)
  58. [A,C]*B + A*[B,C]
  59. >>> Commutator(A, B*C).expand(commutator=True)
  60. [A,B]*C + B*[A,C]
  61. Adjoint operations applied to the commutator are properly applied to the
  62. arguments:
  63. >>> Dagger(Commutator(A, B))
  64. -[Dagger(A),Dagger(B)]
  65. References
  66. ==========
  67. .. [1] https://en.wikipedia.org/wiki/Commutator
  68. """
  69. is_commutative = False
  70. def __new__(cls, A, B):
  71. r = cls.eval(A, B)
  72. if r is not None:
  73. return r
  74. obj = Expr.__new__(cls, A, B)
  75. return obj
  76. @classmethod
  77. def eval(cls, a, b):
  78. if not (a and b):
  79. return S.Zero
  80. if a == b:
  81. return S.Zero
  82. if a.is_commutative or b.is_commutative:
  83. return S.Zero
  84. # [xA,yB] -> xy*[A,B]
  85. ca, nca = a.args_cnc()
  86. cb, ncb = b.args_cnc()
  87. c_part = ca + cb
  88. if c_part:
  89. return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
  90. # Canonical ordering of arguments
  91. # The Commutator [A, B] is in canonical form if A < B.
  92. if a.compare(b) == 1:
  93. return S.NegativeOne*cls(b, a)
  94. def _expand_pow(self, A, B, sign):
  95. exp = A.exp
  96. if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
  97. # nothing to do
  98. return self
  99. base = A.base
  100. if exp.is_negative:
  101. base = A.base**-1
  102. exp = -exp
  103. comm = Commutator(base, B).expand(commutator=True)
  104. result = base**(exp - 1) * comm
  105. for i in range(1, exp):
  106. result += base**(exp - 1 - i) * comm * base**i
  107. return sign*result.expand()
  108. def _eval_expand_commutator(self, **hints):
  109. A = self.args[0]
  110. B = self.args[1]
  111. if isinstance(A, Add):
  112. # [A + B, C] -> [A, C] + [B, C]
  113. sargs = []
  114. for term in A.args:
  115. comm = Commutator(term, B)
  116. if isinstance(comm, Commutator):
  117. comm = comm._eval_expand_commutator()
  118. sargs.append(comm)
  119. return Add(*sargs)
  120. elif isinstance(B, Add):
  121. # [A, B + C] -> [A, B] + [A, C]
  122. sargs = []
  123. for term in B.args:
  124. comm = Commutator(A, term)
  125. if isinstance(comm, Commutator):
  126. comm = comm._eval_expand_commutator()
  127. sargs.append(comm)
  128. return Add(*sargs)
  129. elif isinstance(A, Mul):
  130. # [A*B, C] -> A*[B, C] + [A, C]*B
  131. a = A.args[0]
  132. b = Mul(*A.args[1:])
  133. c = B
  134. comm1 = Commutator(b, c)
  135. comm2 = Commutator(a, c)
  136. if isinstance(comm1, Commutator):
  137. comm1 = comm1._eval_expand_commutator()
  138. if isinstance(comm2, Commutator):
  139. comm2 = comm2._eval_expand_commutator()
  140. first = Mul(a, comm1)
  141. second = Mul(comm2, b)
  142. return Add(first, second)
  143. elif isinstance(B, Mul):
  144. # [A, B*C] -> [A, B]*C + B*[A, C]
  145. a = A
  146. b = B.args[0]
  147. c = Mul(*B.args[1:])
  148. comm1 = Commutator(a, b)
  149. comm2 = Commutator(a, c)
  150. if isinstance(comm1, Commutator):
  151. comm1 = comm1._eval_expand_commutator()
  152. if isinstance(comm2, Commutator):
  153. comm2 = comm2._eval_expand_commutator()
  154. first = Mul(comm1, c)
  155. second = Mul(b, comm2)
  156. return Add(first, second)
  157. elif isinstance(A, Pow):
  158. # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
  159. return self._expand_pow(A, B, 1)
  160. elif isinstance(B, Pow):
  161. # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
  162. return self._expand_pow(B, A, -1)
  163. # No changes, so return self
  164. return self
  165. def doit(self, **hints):
  166. """ Evaluate commutator """
  167. A = self.args[0]
  168. B = self.args[1]
  169. if isinstance(A, Operator) and isinstance(B, Operator):
  170. try:
  171. comm = A._eval_commutator(B, **hints)
  172. except NotImplementedError:
  173. try:
  174. comm = -1*B._eval_commutator(A, **hints)
  175. except NotImplementedError:
  176. comm = None
  177. if comm is not None:
  178. return comm.doit(**hints)
  179. return (A*B - B*A).doit(**hints)
  180. def _eval_adjoint(self):
  181. return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
  182. def _sympyrepr(self, printer, *args):
  183. return "%s(%s,%s)" % (
  184. self.__class__.__name__, printer._print(
  185. self.args[0]), printer._print(self.args[1])
  186. )
  187. def _sympystr(self, printer, *args):
  188. return "[%s,%s]" % (
  189. printer._print(self.args[0]), printer._print(self.args[1]))
  190. def _pretty(self, printer, *args):
  191. pform = printer._print(self.args[0], *args)
  192. pform = prettyForm(*pform.right(prettyForm(',')))
  193. pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
  194. pform = prettyForm(*pform.parens(left='[', right=']'))
  195. return pform
  196. def _latex(self, printer, *args):
  197. return "\\left[%s,%s\\right]" % tuple([
  198. printer._print(arg, *args) for arg in self.args])