dagger.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Hermitian conjugation."""
  2. from sympy.core import Expr, sympify
  3. from sympy.functions.elementary.complexes import adjoint
  4. __all__ = [
  5. 'Dagger'
  6. ]
  7. class Dagger(adjoint):
  8. """General Hermitian conjugate operation.
  9. Explanation
  10. ===========
  11. Take the Hermetian conjugate of an argument [1]_. For matrices this
  12. operation is equivalent to transpose and complex conjugate [2]_.
  13. Parameters
  14. ==========
  15. arg : Expr
  16. The SymPy expression that we want to take the dagger of.
  17. evaluate : bool
  18. Whether the resulting expression should be directly evaluated.
  19. Examples
  20. ========
  21. Daggering various quantum objects:
  22. >>> from sympy.physics.quantum.dagger import Dagger
  23. >>> from sympy.physics.quantum.state import Ket, Bra
  24. >>> from sympy.physics.quantum.operator import Operator
  25. >>> Dagger(Ket('psi'))
  26. <psi|
  27. >>> Dagger(Bra('phi'))
  28. |phi>
  29. >>> Dagger(Operator('A'))
  30. Dagger(A)
  31. Inner and outer products::
  32. >>> from sympy.physics.quantum import InnerProduct, OuterProduct
  33. >>> Dagger(InnerProduct(Bra('a'), Ket('b')))
  34. <b|a>
  35. >>> Dagger(OuterProduct(Ket('a'), Bra('b')))
  36. |b><a|
  37. Powers, sums and products::
  38. >>> A = Operator('A')
  39. >>> B = Operator('B')
  40. >>> Dagger(A*B)
  41. Dagger(B)*Dagger(A)
  42. >>> Dagger(A+B)
  43. Dagger(A) + Dagger(B)
  44. >>> Dagger(A**2)
  45. Dagger(A)**2
  46. Dagger also seamlessly handles complex numbers and matrices::
  47. >>> from sympy import Matrix, I
  48. >>> m = Matrix([[1,I],[2,I]])
  49. >>> m
  50. Matrix([
  51. [1, I],
  52. [2, I]])
  53. >>> Dagger(m)
  54. Matrix([
  55. [ 1, 2],
  56. [-I, -I]])
  57. References
  58. ==========
  59. .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
  60. .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
  61. """
  62. @property
  63. def kind(self):
  64. """Find the kind of a dagger of something (just the kind of the something)."""
  65. return self.args[0].kind
  66. def __new__(cls, arg, evaluate=True):
  67. if hasattr(arg, 'adjoint') and evaluate:
  68. return arg.adjoint()
  69. elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose') and evaluate:
  70. return arg.conjugate().transpose()
  71. return Expr.__new__(cls, sympify(arg))
  72. adjoint.__name__ = "Dagger"
  73. adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])