qexpr.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. from sympy.core.expr import Expr
  2. from sympy.core.symbol import Symbol
  3. from sympy.core.sympify import sympify
  4. from sympy.matrices.dense import Matrix
  5. from sympy.printing.pretty.stringpict import prettyForm
  6. from sympy.core.containers import Tuple
  7. from sympy.utilities.iterables import is_sequence
  8. from sympy.physics.quantum.dagger import Dagger
  9. from sympy.physics.quantum.matrixutils import (
  10. numpy_ndarray, scipy_sparse_matrix,
  11. to_sympy, to_numpy, to_scipy_sparse
  12. )
  13. __all__ = [
  14. 'QuantumError',
  15. 'QExpr'
  16. ]
  17. #-----------------------------------------------------------------------------
  18. # Error handling
  19. #-----------------------------------------------------------------------------
  20. class QuantumError(Exception):
  21. pass
  22. def _qsympify_sequence(seq):
  23. """Convert elements of a sequence to standard form.
  24. This is like sympify, but it performs special logic for arguments passed
  25. to QExpr. The following conversions are done:
  26. * (list, tuple, Tuple) => _qsympify_sequence each element and convert
  27. sequence to a Tuple.
  28. * basestring => Symbol
  29. * Matrix => Matrix
  30. * other => sympify
  31. Strings are passed to Symbol, not sympify to make sure that variables like
  32. 'pi' are kept as Symbols, not the SymPy built-in number subclasses.
  33. Examples
  34. ========
  35. >>> from sympy.physics.quantum.qexpr import _qsympify_sequence
  36. >>> _qsympify_sequence((1,2,[3,4,[1,]]))
  37. (1, 2, (3, 4, (1,)))
  38. """
  39. return tuple(__qsympify_sequence_helper(seq))
  40. def __qsympify_sequence_helper(seq):
  41. """
  42. Helper function for _qsympify_sequence
  43. This function does the actual work.
  44. """
  45. #base case. If not a list, do Sympification
  46. if not is_sequence(seq):
  47. if isinstance(seq, Matrix):
  48. return seq
  49. elif isinstance(seq, str):
  50. return Symbol(seq)
  51. else:
  52. return sympify(seq)
  53. # base condition, when seq is QExpr and also
  54. # is iterable.
  55. if isinstance(seq, QExpr):
  56. return seq
  57. #if list, recurse on each item in the list
  58. result = [__qsympify_sequence_helper(item) for item in seq]
  59. return Tuple(*result)
  60. #-----------------------------------------------------------------------------
  61. # Basic Quantum Expression from which all objects descend
  62. #-----------------------------------------------------------------------------
  63. class QExpr(Expr):
  64. """A base class for all quantum object like operators and states."""
  65. # In sympy, slots are for instance attributes that are computed
  66. # dynamically by the __new__ method. They are not part of args, but they
  67. # derive from args.
  68. # The Hilbert space a quantum Object belongs to.
  69. __slots__ = ('hilbert_space', )
  70. is_commutative = False
  71. # The separator used in printing the label.
  72. _label_separator = ''
  73. def __new__(cls, *args, **kwargs):
  74. """Construct a new quantum object.
  75. Parameters
  76. ==========
  77. args : tuple
  78. The list of numbers or parameters that uniquely specify the
  79. quantum object. For a state, this will be its symbol or its
  80. set of quantum numbers.
  81. Examples
  82. ========
  83. >>> from sympy.physics.quantum.qexpr import QExpr
  84. >>> q = QExpr(0)
  85. >>> q
  86. 0
  87. >>> q.label
  88. (0,)
  89. >>> q.hilbert_space
  90. H
  91. >>> q.args
  92. (0,)
  93. >>> q.is_commutative
  94. False
  95. """
  96. # First compute args and call Expr.__new__ to create the instance
  97. args = cls._eval_args(args, **kwargs)
  98. if len(args) == 0:
  99. args = cls._eval_args(tuple(cls.default_args()), **kwargs)
  100. inst = Expr.__new__(cls, *args)
  101. # Now set the slots on the instance
  102. inst.hilbert_space = cls._eval_hilbert_space(args)
  103. return inst
  104. @classmethod
  105. def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
  106. """Create new instance of this class with hilbert_space and args.
  107. This is used to bypass the more complex logic in the ``__new__``
  108. method in cases where you already have the exact ``hilbert_space``
  109. and ``args``. This should be used when you are positive these
  110. arguments are valid, in their final, proper form and want to optimize
  111. the creation of the object.
  112. """
  113. obj = Expr.__new__(cls, *args, **old_assumptions)
  114. obj.hilbert_space = hilbert_space
  115. return obj
  116. #-------------------------------------------------------------------------
  117. # Properties
  118. #-------------------------------------------------------------------------
  119. @property
  120. def label(self):
  121. """The label is the unique set of identifiers for the object.
  122. Usually, this will include all of the information about the state
  123. *except* the time (in the case of time-dependent objects).
  124. This must be a tuple, rather than a Tuple.
  125. """
  126. if len(self.args) == 0: # If there is no label specified, return the default
  127. return self._eval_args(list(self.default_args()))
  128. else:
  129. return self.args
  130. @property
  131. def is_symbolic(self):
  132. return True
  133. @classmethod
  134. def default_args(self):
  135. """If no arguments are specified, then this will return a default set
  136. of arguments to be run through the constructor.
  137. NOTE: Any classes that override this MUST return a tuple of arguments.
  138. Should be overridden by subclasses to specify the default arguments for kets and operators
  139. """
  140. raise NotImplementedError("No default arguments for this class!")
  141. #-------------------------------------------------------------------------
  142. # _eval_* methods
  143. #-------------------------------------------------------------------------
  144. def _eval_adjoint(self):
  145. obj = Expr._eval_adjoint(self)
  146. if obj is None:
  147. obj = Expr.__new__(Dagger, self)
  148. if isinstance(obj, QExpr):
  149. obj.hilbert_space = self.hilbert_space
  150. return obj
  151. @classmethod
  152. def _eval_args(cls, args):
  153. """Process the args passed to the __new__ method.
  154. This simply runs args through _qsympify_sequence.
  155. """
  156. return _qsympify_sequence(args)
  157. @classmethod
  158. def _eval_hilbert_space(cls, args):
  159. """Compute the Hilbert space instance from the args.
  160. """
  161. from sympy.physics.quantum.hilbert import HilbertSpace
  162. return HilbertSpace()
  163. #-------------------------------------------------------------------------
  164. # Printing
  165. #-------------------------------------------------------------------------
  166. # Utilities for printing: these operate on raw SymPy objects
  167. def _print_sequence(self, seq, sep, printer, *args):
  168. result = []
  169. for item in seq:
  170. result.append(printer._print(item, *args))
  171. return sep.join(result)
  172. def _print_sequence_pretty(self, seq, sep, printer, *args):
  173. pform = printer._print(seq[0], *args)
  174. for item in seq[1:]:
  175. pform = prettyForm(*pform.right(sep))
  176. pform = prettyForm(*pform.right(printer._print(item, *args)))
  177. return pform
  178. # Utilities for printing: these operate prettyForm objects
  179. def _print_subscript_pretty(self, a, b):
  180. top = prettyForm(*b.left(' '*a.width()))
  181. bot = prettyForm(*a.right(' '*b.width()))
  182. return prettyForm(binding=prettyForm.POW, *bot.below(top))
  183. def _print_superscript_pretty(self, a, b):
  184. return a**b
  185. def _print_parens_pretty(self, pform, left='(', right=')'):
  186. return prettyForm(*pform.parens(left=left, right=right))
  187. # Printing of labels (i.e. args)
  188. def _print_label(self, printer, *args):
  189. """Prints the label of the QExpr
  190. This method prints self.label, using self._label_separator to separate
  191. the elements. This method should not be overridden, instead, override
  192. _print_contents to change printing behavior.
  193. """
  194. return self._print_sequence(
  195. self.label, self._label_separator, printer, *args
  196. )
  197. def _print_label_repr(self, printer, *args):
  198. return self._print_sequence(
  199. self.label, ',', printer, *args
  200. )
  201. def _print_label_pretty(self, printer, *args):
  202. return self._print_sequence_pretty(
  203. self.label, self._label_separator, printer, *args
  204. )
  205. def _print_label_latex(self, printer, *args):
  206. return self._print_sequence(
  207. self.label, self._label_separator, printer, *args
  208. )
  209. # Printing of contents (default to label)
  210. def _print_contents(self, printer, *args):
  211. """Printer for contents of QExpr
  212. Handles the printing of any unique identifying contents of a QExpr to
  213. print as its contents, such as any variables or quantum numbers. The
  214. default is to print the label, which is almost always the args. This
  215. should not include printing of any brackets or parentheses.
  216. """
  217. return self._print_label(printer, *args)
  218. def _print_contents_pretty(self, printer, *args):
  219. return self._print_label_pretty(printer, *args)
  220. def _print_contents_latex(self, printer, *args):
  221. return self._print_label_latex(printer, *args)
  222. # Main printing methods
  223. def _sympystr(self, printer, *args):
  224. """Default printing behavior of QExpr objects
  225. Handles the default printing of a QExpr. To add other things to the
  226. printing of the object, such as an operator name to operators or
  227. brackets to states, the class should override the _print/_pretty/_latex
  228. functions directly and make calls to _print_contents where appropriate.
  229. This allows things like InnerProduct to easily control its printing the
  230. printing of contents.
  231. """
  232. return self._print_contents(printer, *args)
  233. def _sympyrepr(self, printer, *args):
  234. classname = self.__class__.__name__
  235. label = self._print_label_repr(printer, *args)
  236. return '%s(%s)' % (classname, label)
  237. def _pretty(self, printer, *args):
  238. pform = self._print_contents_pretty(printer, *args)
  239. return pform
  240. def _latex(self, printer, *args):
  241. return self._print_contents_latex(printer, *args)
  242. #-------------------------------------------------------------------------
  243. # Represent
  244. #-------------------------------------------------------------------------
  245. def _represent_default_basis(self, **options):
  246. raise NotImplementedError('This object does not have a default basis')
  247. def _represent(self, *, basis=None, **options):
  248. """Represent this object in a given basis.
  249. This method dispatches to the actual methods that perform the
  250. representation. Subclases of QExpr should define various methods to
  251. determine how the object will be represented in various bases. The
  252. format of these methods is::
  253. def _represent_BasisName(self, basis, **options):
  254. Thus to define how a quantum object is represented in the basis of
  255. the operator Position, you would define::
  256. def _represent_Position(self, basis, **options):
  257. Usually, basis object will be instances of Operator subclasses, but
  258. there is a chance we will relax this in the future to accommodate other
  259. types of basis sets that are not associated with an operator.
  260. If the ``format`` option is given it can be ("sympy", "numpy",
  261. "scipy.sparse"). This will ensure that any matrices that result from
  262. representing the object are returned in the appropriate matrix format.
  263. Parameters
  264. ==========
  265. basis : Operator
  266. The Operator whose basis functions will be used as the basis for
  267. representation.
  268. options : dict
  269. A dictionary of key/value pairs that give options and hints for
  270. the representation, such as the number of basis functions to
  271. be used.
  272. """
  273. if basis is None:
  274. result = self._represent_default_basis(**options)
  275. else:
  276. result = dispatch_method(self, '_represent', basis, **options)
  277. # If we get a matrix representation, convert it to the right format.
  278. format = options.get('format', 'sympy')
  279. result = self._format_represent(result, format)
  280. return result
  281. def _format_represent(self, result, format):
  282. if format == 'sympy' and not isinstance(result, Matrix):
  283. return to_sympy(result)
  284. elif format == 'numpy' and not isinstance(result, numpy_ndarray):
  285. return to_numpy(result)
  286. elif format == 'scipy.sparse' and \
  287. not isinstance(result, scipy_sparse_matrix):
  288. return to_scipy_sparse(result)
  289. return result
  290. def split_commutative_parts(e):
  291. """Split into commutative and non-commutative parts."""
  292. c_part, nc_part = e.args_cnc()
  293. c_part = list(c_part)
  294. return c_part, nc_part
  295. def split_qexpr_parts(e):
  296. """Split an expression into Expr and noncommutative QExpr parts."""
  297. expr_part = []
  298. qexpr_part = []
  299. for arg in e.args:
  300. if not isinstance(arg, QExpr):
  301. expr_part.append(arg)
  302. else:
  303. qexpr_part.append(arg)
  304. return expr_part, qexpr_part
  305. def dispatch_method(self, basename, arg, **options):
  306. """Dispatch a method to the proper handlers."""
  307. method_name = '%s_%s' % (basename, arg.__class__.__name__)
  308. if hasattr(self, method_name):
  309. f = getattr(self, method_name)
  310. # This can raise and we will allow it to propagate.
  311. result = f(arg, **options)
  312. if result is not None:
  313. return result
  314. raise NotImplementedError(
  315. "%s.%s cannot handle: %r" %
  316. (self.__class__.__name__, basename, arg)
  317. )