dagger.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """Hermitian conjugation."""
  2. from sympy.core import Expr, Mul
  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. Examples
  18. ========
  19. Daggering various quantum objects:
  20. >>> from sympy.physics.quantum.dagger import Dagger
  21. >>> from sympy.physics.quantum.state import Ket, Bra
  22. >>> from sympy.physics.quantum.operator import Operator
  23. >>> Dagger(Ket('psi'))
  24. <psi|
  25. >>> Dagger(Bra('phi'))
  26. |phi>
  27. >>> Dagger(Operator('A'))
  28. Dagger(A)
  29. Inner and outer products::
  30. >>> from sympy.physics.quantum import InnerProduct, OuterProduct
  31. >>> Dagger(InnerProduct(Bra('a'), Ket('b')))
  32. <b|a>
  33. >>> Dagger(OuterProduct(Ket('a'), Bra('b')))
  34. |b><a|
  35. Powers, sums and products::
  36. >>> A = Operator('A')
  37. >>> B = Operator('B')
  38. >>> Dagger(A*B)
  39. Dagger(B)*Dagger(A)
  40. >>> Dagger(A+B)
  41. Dagger(A) + Dagger(B)
  42. >>> Dagger(A**2)
  43. Dagger(A)**2
  44. Dagger also seamlessly handles complex numbers and matrices::
  45. >>> from sympy import Matrix, I
  46. >>> m = Matrix([[1,I],[2,I]])
  47. >>> m
  48. Matrix([
  49. [1, I],
  50. [2, I]])
  51. >>> Dagger(m)
  52. Matrix([
  53. [ 1, 2],
  54. [-I, -I]])
  55. References
  56. ==========
  57. .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
  58. .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
  59. """
  60. def __new__(cls, arg):
  61. if hasattr(arg, 'adjoint'):
  62. obj = arg.adjoint()
  63. elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'):
  64. obj = arg.conjugate().transpose()
  65. if obj is not None:
  66. return obj
  67. return Expr.__new__(cls, arg)
  68. def __mul__(self, other):
  69. from sympy.physics.quantum import IdentityOperator
  70. if isinstance(other, IdentityOperator):
  71. return self
  72. return Mul(self, other)
  73. adjoint.__name__ = "Dagger"
  74. adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])