spin.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149
  1. """Quantum mechanical angular momemtum."""
  2. from sympy.concrete.summations import Sum
  3. from sympy.core.add import Add
  4. from sympy.core.containers import Tuple
  5. from sympy.core.expr import Expr
  6. from sympy.core.mul import Mul
  7. from sympy.core.numbers import (I, Integer, Rational, pi)
  8. from sympy.core.singleton import S
  9. from sympy.core.symbol import (Dummy, symbols)
  10. from sympy.core.sympify import sympify
  11. from sympy.functions.combinatorial.factorials import (binomial, factorial)
  12. from sympy.functions.elementary.exponential import exp
  13. from sympy.functions.elementary.miscellaneous import sqrt
  14. from sympy.functions.elementary.trigonometric import (cos, sin)
  15. from sympy.simplify.simplify import simplify
  16. from sympy.matrices import zeros
  17. from sympy.printing.pretty.stringpict import prettyForm, stringPict
  18. from sympy.printing.pretty.pretty_symbology import pretty_symbol
  19. from sympy.physics.quantum.qexpr import QExpr
  20. from sympy.physics.quantum.operator import (HermitianOperator, Operator,
  21. UnitaryOperator)
  22. from sympy.physics.quantum.state import Bra, Ket, State
  23. from sympy.functions.special.tensor_functions import KroneckerDelta
  24. from sympy.physics.quantum.constants import hbar
  25. from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
  26. from sympy.physics.quantum.tensorproduct import TensorProduct
  27. from sympy.physics.quantum.cg import CG
  28. from sympy.physics.quantum.qapply import qapply
  29. __all__ = [
  30. 'm_values',
  31. 'Jplus',
  32. 'Jminus',
  33. 'Jx',
  34. 'Jy',
  35. 'Jz',
  36. 'J2',
  37. 'Rotation',
  38. 'WignerD',
  39. 'JxKet',
  40. 'JxBra',
  41. 'JyKet',
  42. 'JyBra',
  43. 'JzKet',
  44. 'JzBra',
  45. 'JzOp',
  46. 'J2Op',
  47. 'JxKetCoupled',
  48. 'JxBraCoupled',
  49. 'JyKetCoupled',
  50. 'JyBraCoupled',
  51. 'JzKetCoupled',
  52. 'JzBraCoupled',
  53. 'couple',
  54. 'uncouple'
  55. ]
  56. def m_values(j):
  57. j = sympify(j)
  58. size = 2*j + 1
  59. if not size.is_Integer or not size > 0:
  60. raise ValueError(
  61. 'Only integer or half-integer values allowed for j, got: : %r' % j
  62. )
  63. return size, [j - i for i in range(int(2*j + 1))]
  64. #-----------------------------------------------------------------------------
  65. # Spin Operators
  66. #-----------------------------------------------------------------------------
  67. class SpinOpBase:
  68. """Base class for spin operators."""
  69. @classmethod
  70. def _eval_hilbert_space(cls, label):
  71. # We consider all j values so our space is infinite.
  72. return ComplexSpace(S.Infinity)
  73. @property
  74. def name(self):
  75. return self.args[0]
  76. def _print_contents(self, printer, *args):
  77. return '%s%s' % (self.name, self._coord)
  78. def _print_contents_pretty(self, printer, *args):
  79. a = stringPict(str(self.name))
  80. b = stringPict(self._coord)
  81. return self._print_subscript_pretty(a, b)
  82. def _print_contents_latex(self, printer, *args):
  83. return r'%s_%s' % ((self.name, self._coord))
  84. def _represent_base(self, basis, **options):
  85. j = options.get('j', S.Half)
  86. size, mvals = m_values(j)
  87. result = zeros(size, size)
  88. for p in range(size):
  89. for q in range(size):
  90. me = self.matrix_element(j, mvals[p], j, mvals[q])
  91. result[p, q] = me
  92. return result
  93. def _apply_op(self, ket, orig_basis, **options):
  94. state = ket.rewrite(self.basis)
  95. # If the state has only one term
  96. if isinstance(state, State):
  97. ret = (hbar*state.m)*state
  98. # state is a linear combination of states
  99. elif isinstance(state, Sum):
  100. ret = self._apply_operator_Sum(state, **options)
  101. else:
  102. ret = qapply(self*state)
  103. if ret == self*state:
  104. raise NotImplementedError
  105. return ret.rewrite(orig_basis)
  106. def _apply_operator_JxKet(self, ket, **options):
  107. return self._apply_op(ket, 'Jx', **options)
  108. def _apply_operator_JxKetCoupled(self, ket, **options):
  109. return self._apply_op(ket, 'Jx', **options)
  110. def _apply_operator_JyKet(self, ket, **options):
  111. return self._apply_op(ket, 'Jy', **options)
  112. def _apply_operator_JyKetCoupled(self, ket, **options):
  113. return self._apply_op(ket, 'Jy', **options)
  114. def _apply_operator_JzKet(self, ket, **options):
  115. return self._apply_op(ket, 'Jz', **options)
  116. def _apply_operator_JzKetCoupled(self, ket, **options):
  117. return self._apply_op(ket, 'Jz', **options)
  118. def _apply_operator_TensorProduct(self, tp, **options):
  119. # Uncoupling operator is only easily found for coordinate basis spin operators
  120. # TODO: add methods for uncoupling operators
  121. if not isinstance(self, (JxOp, JyOp, JzOp)):
  122. raise NotImplementedError
  123. result = []
  124. for n in range(len(tp.args)):
  125. arg = []
  126. arg.extend(tp.args[:n])
  127. arg.append(self._apply_operator(tp.args[n]))
  128. arg.extend(tp.args[n + 1:])
  129. result.append(tp.__class__(*arg))
  130. return Add(*result).expand()
  131. # TODO: move this to qapply_Mul
  132. def _apply_operator_Sum(self, s, **options):
  133. new_func = qapply(self*s.function)
  134. if new_func == self*s.function:
  135. raise NotImplementedError
  136. return Sum(new_func, *s.limits)
  137. def _eval_trace(self, **options):
  138. #TODO: use options to use different j values
  139. #For now eval at default basis
  140. # is it efficient to represent each time
  141. # to do a trace?
  142. return self._represent_default_basis().trace()
  143. class JplusOp(SpinOpBase, Operator):
  144. """The J+ operator."""
  145. _coord = '+'
  146. basis = 'Jz'
  147. def _eval_commutator_JminusOp(self, other):
  148. return 2*hbar*JzOp(self.name)
  149. def _apply_operator_JzKet(self, ket, **options):
  150. j = ket.j
  151. m = ket.m
  152. if m.is_Number and j.is_Number:
  153. if m >= j:
  154. return S.Zero
  155. return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
  156. def _apply_operator_JzKetCoupled(self, ket, **options):
  157. j = ket.j
  158. m = ket.m
  159. jn = ket.jn
  160. coupling = ket.coupling
  161. if m.is_Number and j.is_Number:
  162. if m >= j:
  163. return S.Zero
  164. return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
  165. def matrix_element(self, j, m, jp, mp):
  166. result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
  167. result *= KroneckerDelta(m, mp + 1)
  168. result *= KroneckerDelta(j, jp)
  169. return result
  170. def _represent_default_basis(self, **options):
  171. return self._represent_JzOp(None, **options)
  172. def _represent_JzOp(self, basis, **options):
  173. return self._represent_base(basis, **options)
  174. def _eval_rewrite_as_xyz(self, *args, **kwargs):
  175. return JxOp(args[0]) + I*JyOp(args[0])
  176. class JminusOp(SpinOpBase, Operator):
  177. """The J- operator."""
  178. _coord = '-'
  179. basis = 'Jz'
  180. def _apply_operator_JzKet(self, ket, **options):
  181. j = ket.j
  182. m = ket.m
  183. if m.is_Number and j.is_Number:
  184. if m <= -j:
  185. return S.Zero
  186. return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
  187. def _apply_operator_JzKetCoupled(self, ket, **options):
  188. j = ket.j
  189. m = ket.m
  190. jn = ket.jn
  191. coupling = ket.coupling
  192. if m.is_Number and j.is_Number:
  193. if m <= -j:
  194. return S.Zero
  195. return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
  196. def matrix_element(self, j, m, jp, mp):
  197. result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
  198. result *= KroneckerDelta(m, mp - 1)
  199. result *= KroneckerDelta(j, jp)
  200. return result
  201. def _represent_default_basis(self, **options):
  202. return self._represent_JzOp(None, **options)
  203. def _represent_JzOp(self, basis, **options):
  204. return self._represent_base(basis, **options)
  205. def _eval_rewrite_as_xyz(self, *args, **kwargs):
  206. return JxOp(args[0]) - I*JyOp(args[0])
  207. class JxOp(SpinOpBase, HermitianOperator):
  208. """The Jx operator."""
  209. _coord = 'x'
  210. basis = 'Jx'
  211. def _eval_commutator_JyOp(self, other):
  212. return I*hbar*JzOp(self.name)
  213. def _eval_commutator_JzOp(self, other):
  214. return -I*hbar*JyOp(self.name)
  215. def _apply_operator_JzKet(self, ket, **options):
  216. jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
  217. jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
  218. return (jp + jm)/Integer(2)
  219. def _apply_operator_JzKetCoupled(self, ket, **options):
  220. jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
  221. jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
  222. return (jp + jm)/Integer(2)
  223. def _represent_default_basis(self, **options):
  224. return self._represent_JzOp(None, **options)
  225. def _represent_JzOp(self, basis, **options):
  226. jp = JplusOp(self.name)._represent_JzOp(basis, **options)
  227. jm = JminusOp(self.name)._represent_JzOp(basis, **options)
  228. return (jp + jm)/Integer(2)
  229. def _eval_rewrite_as_plusminus(self, *args, **kwargs):
  230. return (JplusOp(args[0]) + JminusOp(args[0]))/2
  231. class JyOp(SpinOpBase, HermitianOperator):
  232. """The Jy operator."""
  233. _coord = 'y'
  234. basis = 'Jy'
  235. def _eval_commutator_JzOp(self, other):
  236. return I*hbar*JxOp(self.name)
  237. def _eval_commutator_JxOp(self, other):
  238. return -I*hbar*J2Op(self.name)
  239. def _apply_operator_JzKet(self, ket, **options):
  240. jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
  241. jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
  242. return (jp - jm)/(Integer(2)*I)
  243. def _apply_operator_JzKetCoupled(self, ket, **options):
  244. jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
  245. jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
  246. return (jp - jm)/(Integer(2)*I)
  247. def _represent_default_basis(self, **options):
  248. return self._represent_JzOp(None, **options)
  249. def _represent_JzOp(self, basis, **options):
  250. jp = JplusOp(self.name)._represent_JzOp(basis, **options)
  251. jm = JminusOp(self.name)._represent_JzOp(basis, **options)
  252. return (jp - jm)/(Integer(2)*I)
  253. def _eval_rewrite_as_plusminus(self, *args, **kwargs):
  254. return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
  255. class JzOp(SpinOpBase, HermitianOperator):
  256. """The Jz operator."""
  257. _coord = 'z'
  258. basis = 'Jz'
  259. def _eval_commutator_JxOp(self, other):
  260. return I*hbar*JyOp(self.name)
  261. def _eval_commutator_JyOp(self, other):
  262. return -I*hbar*JxOp(self.name)
  263. def _eval_commutator_JplusOp(self, other):
  264. return hbar*JplusOp(self.name)
  265. def _eval_commutator_JminusOp(self, other):
  266. return -hbar*JminusOp(self.name)
  267. def matrix_element(self, j, m, jp, mp):
  268. result = hbar*mp
  269. result *= KroneckerDelta(m, mp)
  270. result *= KroneckerDelta(j, jp)
  271. return result
  272. def _represent_default_basis(self, **options):
  273. return self._represent_JzOp(None, **options)
  274. def _represent_JzOp(self, basis, **options):
  275. return self._represent_base(basis, **options)
  276. class J2Op(SpinOpBase, HermitianOperator):
  277. """The J^2 operator."""
  278. _coord = '2'
  279. def _eval_commutator_JxOp(self, other):
  280. return S.Zero
  281. def _eval_commutator_JyOp(self, other):
  282. return S.Zero
  283. def _eval_commutator_JzOp(self, other):
  284. return S.Zero
  285. def _eval_commutator_JplusOp(self, other):
  286. return S.Zero
  287. def _eval_commutator_JminusOp(self, other):
  288. return S.Zero
  289. def _apply_operator_JxKet(self, ket, **options):
  290. j = ket.j
  291. return hbar**2*j*(j + 1)*ket
  292. def _apply_operator_JxKetCoupled(self, ket, **options):
  293. j = ket.j
  294. return hbar**2*j*(j + 1)*ket
  295. def _apply_operator_JyKet(self, ket, **options):
  296. j = ket.j
  297. return hbar**2*j*(j + 1)*ket
  298. def _apply_operator_JyKetCoupled(self, ket, **options):
  299. j = ket.j
  300. return hbar**2*j*(j + 1)*ket
  301. def _apply_operator_JzKet(self, ket, **options):
  302. j = ket.j
  303. return hbar**2*j*(j + 1)*ket
  304. def _apply_operator_JzKetCoupled(self, ket, **options):
  305. j = ket.j
  306. return hbar**2*j*(j + 1)*ket
  307. def matrix_element(self, j, m, jp, mp):
  308. result = (hbar**2)*j*(j + 1)
  309. result *= KroneckerDelta(m, mp)
  310. result *= KroneckerDelta(j, jp)
  311. return result
  312. def _represent_default_basis(self, **options):
  313. return self._represent_JzOp(None, **options)
  314. def _represent_JzOp(self, basis, **options):
  315. return self._represent_base(basis, **options)
  316. def _print_contents_pretty(self, printer, *args):
  317. a = prettyForm(str(self.name))
  318. b = prettyForm('2')
  319. return a**b
  320. def _print_contents_latex(self, printer, *args):
  321. return r'%s^2' % str(self.name)
  322. def _eval_rewrite_as_xyz(self, *args, **kwargs):
  323. return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
  324. def _eval_rewrite_as_plusminus(self, *args, **kwargs):
  325. a = args[0]
  326. return JzOp(a)**2 + \
  327. S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
  328. class Rotation(UnitaryOperator):
  329. """Wigner D operator in terms of Euler angles.
  330. Defines the rotation operator in terms of the Euler angles defined by
  331. the z-y-z convention for a passive transformation. That is the coordinate
  332. axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
  333. this new coordinate system is rotated about the new y'-axis, giving new
  334. x''-y''-z'' axes. Then this new coordinate system is rotated about the
  335. z''-axis. Conventions follow those laid out in [1]_.
  336. Parameters
  337. ==========
  338. alpha : Number, Symbol
  339. First Euler Angle
  340. beta : Number, Symbol
  341. Second Euler angle
  342. gamma : Number, Symbol
  343. Third Euler angle
  344. Examples
  345. ========
  346. A simple example rotation operator:
  347. >>> from sympy import pi
  348. >>> from sympy.physics.quantum.spin import Rotation
  349. >>> Rotation(pi, 0, pi/2)
  350. R(pi,0,pi/2)
  351. With symbolic Euler angles and calculating the inverse rotation operator:
  352. >>> from sympy import symbols
  353. >>> a, b, c = symbols('a b c')
  354. >>> Rotation(a, b, c)
  355. R(a,b,c)
  356. >>> Rotation(a, b, c).inverse()
  357. R(-c,-b,-a)
  358. See Also
  359. ========
  360. WignerD: Symbolic Wigner-D function
  361. D: Wigner-D function
  362. d: Wigner small-d function
  363. References
  364. ==========
  365. .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
  366. """
  367. @classmethod
  368. def _eval_args(cls, args):
  369. args = QExpr._eval_args(args)
  370. if len(args) != 3:
  371. raise ValueError('3 Euler angles required, got: %r' % args)
  372. return args
  373. @classmethod
  374. def _eval_hilbert_space(cls, label):
  375. # We consider all j values so our space is infinite.
  376. return ComplexSpace(S.Infinity)
  377. @property
  378. def alpha(self):
  379. return self.label[0]
  380. @property
  381. def beta(self):
  382. return self.label[1]
  383. @property
  384. def gamma(self):
  385. return self.label[2]
  386. def _print_operator_name(self, printer, *args):
  387. return 'R'
  388. def _print_operator_name_pretty(self, printer, *args):
  389. if printer._use_unicode:
  390. return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
  391. else:
  392. return prettyForm("R ")
  393. def _print_operator_name_latex(self, printer, *args):
  394. return r'\mathcal{R}'
  395. def _eval_inverse(self):
  396. return Rotation(-self.gamma, -self.beta, -self.alpha)
  397. @classmethod
  398. def D(cls, j, m, mp, alpha, beta, gamma):
  399. """Wigner D-function.
  400. Returns an instance of the WignerD class corresponding to the Wigner-D
  401. function specified by the parameters.
  402. Parameters
  403. ===========
  404. j : Number
  405. Total angular momentum
  406. m : Number
  407. Eigenvalue of angular momentum along axis after rotation
  408. mp : Number
  409. Eigenvalue of angular momentum along rotated axis
  410. alpha : Number, Symbol
  411. First Euler angle of rotation
  412. beta : Number, Symbol
  413. Second Euler angle of rotation
  414. gamma : Number, Symbol
  415. Third Euler angle of rotation
  416. Examples
  417. ========
  418. Return the Wigner-D matrix element for a defined rotation, both
  419. numerical and symbolic:
  420. >>> from sympy.physics.quantum.spin import Rotation
  421. >>> from sympy import pi, symbols
  422. >>> alpha, beta, gamma = symbols('alpha beta gamma')
  423. >>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
  424. WignerD(1, 1, 0, pi, pi/2, -pi)
  425. See Also
  426. ========
  427. WignerD: Symbolic Wigner-D function
  428. """
  429. return WignerD(j, m, mp, alpha, beta, gamma)
  430. @classmethod
  431. def d(cls, j, m, mp, beta):
  432. """Wigner small-d function.
  433. Returns an instance of the WignerD class corresponding to the Wigner-D
  434. function specified by the parameters with the alpha and gamma angles
  435. given as 0.
  436. Parameters
  437. ===========
  438. j : Number
  439. Total angular momentum
  440. m : Number
  441. Eigenvalue of angular momentum along axis after rotation
  442. mp : Number
  443. Eigenvalue of angular momentum along rotated axis
  444. beta : Number, Symbol
  445. Second Euler angle of rotation
  446. Examples
  447. ========
  448. Return the Wigner-D matrix element for a defined rotation, both
  449. numerical and symbolic:
  450. >>> from sympy.physics.quantum.spin import Rotation
  451. >>> from sympy import pi, symbols
  452. >>> beta = symbols('beta')
  453. >>> Rotation.d(1, 1, 0, pi/2)
  454. WignerD(1, 1, 0, 0, pi/2, 0)
  455. See Also
  456. ========
  457. WignerD: Symbolic Wigner-D function
  458. """
  459. return WignerD(j, m, mp, 0, beta, 0)
  460. def matrix_element(self, j, m, jp, mp):
  461. result = self.__class__.D(
  462. jp, m, mp, self.alpha, self.beta, self.gamma
  463. )
  464. result *= KroneckerDelta(j, jp)
  465. return result
  466. def _represent_base(self, basis, **options):
  467. j = sympify(options.get('j', S.Half))
  468. # TODO: move evaluation up to represent function/implement elsewhere
  469. evaluate = sympify(options.get('doit'))
  470. size, mvals = m_values(j)
  471. result = zeros(size, size)
  472. for p in range(size):
  473. for q in range(size):
  474. me = self.matrix_element(j, mvals[p], j, mvals[q])
  475. if evaluate:
  476. result[p, q] = me.doit()
  477. else:
  478. result[p, q] = me
  479. return result
  480. def _represent_default_basis(self, **options):
  481. return self._represent_JzOp(None, **options)
  482. def _represent_JzOp(self, basis, **options):
  483. return self._represent_base(basis, **options)
  484. def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
  485. a = self.alpha
  486. b = self.beta
  487. g = self.gamma
  488. j = ket.j
  489. m = ket.m
  490. if j.is_number:
  491. s = []
  492. size = m_values(j)
  493. sz = size[1]
  494. for mp in sz:
  495. r = Rotation.D(j, m, mp, a, b, g)
  496. z = r.doit()
  497. s.append(z*state(j, mp))
  498. return Add(*s)
  499. else:
  500. if dummy:
  501. mp = Dummy('mp')
  502. else:
  503. mp = symbols('mp')
  504. return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
  505. def _apply_operator_JxKet(self, ket, **options):
  506. return self._apply_operator_uncoupled(JxKet, ket, **options)
  507. def _apply_operator_JyKet(self, ket, **options):
  508. return self._apply_operator_uncoupled(JyKet, ket, **options)
  509. def _apply_operator_JzKet(self, ket, **options):
  510. return self._apply_operator_uncoupled(JzKet, ket, **options)
  511. def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
  512. a = self.alpha
  513. b = self.beta
  514. g = self.gamma
  515. j = ket.j
  516. m = ket.m
  517. jn = ket.jn
  518. coupling = ket.coupling
  519. if j.is_number:
  520. s = []
  521. size = m_values(j)
  522. sz = size[1]
  523. for mp in sz:
  524. r = Rotation.D(j, m, mp, a, b, g)
  525. z = r.doit()
  526. s.append(z*state(j, mp, jn, coupling))
  527. return Add(*s)
  528. else:
  529. if dummy:
  530. mp = Dummy('mp')
  531. else:
  532. mp = symbols('mp')
  533. return Sum(Rotation.D(j, m, mp, a, b, g)*state(
  534. j, mp, jn, coupling), (mp, -j, j))
  535. def _apply_operator_JxKetCoupled(self, ket, **options):
  536. return self._apply_operator_coupled(JxKetCoupled, ket, **options)
  537. def _apply_operator_JyKetCoupled(self, ket, **options):
  538. return self._apply_operator_coupled(JyKetCoupled, ket, **options)
  539. def _apply_operator_JzKetCoupled(self, ket, **options):
  540. return self._apply_operator_coupled(JzKetCoupled, ket, **options)
  541. class WignerD(Expr):
  542. r"""Wigner-D function
  543. The Wigner D-function gives the matrix elements of the rotation
  544. operator in the jm-representation. For the Euler angles `\alpha`,
  545. `\beta`, `\gamma`, the D-function is defined such that:
  546. .. math ::
  547. <j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
  548. Where the rotation operator is as defined by the Rotation class [1]_.
  549. The Wigner D-function defined in this way gives:
  550. .. math ::
  551. D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
  552. Where d is the Wigner small-d function, which is given by Rotation.d.
  553. The Wigner small-d function gives the component of the Wigner
  554. D-function that is determined by the second Euler angle. That is the
  555. Wigner D-function is:
  556. .. math ::
  557. D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
  558. Where d is the small-d function. The Wigner D-function is given by
  559. Rotation.D.
  560. Note that to evaluate the D-function, the j, m and mp parameters must
  561. be integer or half integer numbers.
  562. Parameters
  563. ==========
  564. j : Number
  565. Total angular momentum
  566. m : Number
  567. Eigenvalue of angular momentum along axis after rotation
  568. mp : Number
  569. Eigenvalue of angular momentum along rotated axis
  570. alpha : Number, Symbol
  571. First Euler angle of rotation
  572. beta : Number, Symbol
  573. Second Euler angle of rotation
  574. gamma : Number, Symbol
  575. Third Euler angle of rotation
  576. Examples
  577. ========
  578. Evaluate the Wigner-D matrix elements of a simple rotation:
  579. >>> from sympy.physics.quantum.spin import Rotation
  580. >>> from sympy import pi
  581. >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
  582. >>> rot
  583. WignerD(1, 1, 0, pi, pi/2, 0)
  584. >>> rot.doit()
  585. sqrt(2)/2
  586. Evaluate the Wigner-d matrix elements of a simple rotation
  587. >>> rot = Rotation.d(1, 1, 0, pi/2)
  588. >>> rot
  589. WignerD(1, 1, 0, 0, pi/2, 0)
  590. >>> rot.doit()
  591. -sqrt(2)/2
  592. See Also
  593. ========
  594. Rotation: Rotation operator
  595. References
  596. ==========
  597. .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
  598. """
  599. is_commutative = True
  600. def __new__(cls, *args, **hints):
  601. if not len(args) == 6:
  602. raise ValueError('6 parameters expected, got %s' % args)
  603. args = sympify(args)
  604. evaluate = hints.get('evaluate', False)
  605. if evaluate:
  606. return Expr.__new__(cls, *args)._eval_wignerd()
  607. return Expr.__new__(cls, *args)
  608. @property
  609. def j(self):
  610. return self.args[0]
  611. @property
  612. def m(self):
  613. return self.args[1]
  614. @property
  615. def mp(self):
  616. return self.args[2]
  617. @property
  618. def alpha(self):
  619. return self.args[3]
  620. @property
  621. def beta(self):
  622. return self.args[4]
  623. @property
  624. def gamma(self):
  625. return self.args[5]
  626. def _latex(self, printer, *args):
  627. if self.alpha == 0 and self.gamma == 0:
  628. return r'd^{%s}_{%s,%s}\left(%s\right)' % \
  629. (
  630. printer._print(self.j), printer._print(
  631. self.m), printer._print(self.mp),
  632. printer._print(self.beta) )
  633. return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
  634. (
  635. printer._print(
  636. self.j), printer._print(self.m), printer._print(self.mp),
  637. printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
  638. def _pretty(self, printer, *args):
  639. top = printer._print(self.j)
  640. bot = printer._print(self.m)
  641. bot = prettyForm(*bot.right(','))
  642. bot = prettyForm(*bot.right(printer._print(self.mp)))
  643. pad = max(top.width(), bot.width())
  644. top = prettyForm(*top.left(' '))
  645. bot = prettyForm(*bot.left(' '))
  646. if pad > top.width():
  647. top = prettyForm(*top.right(' '*(pad - top.width())))
  648. if pad > bot.width():
  649. bot = prettyForm(*bot.right(' '*(pad - bot.width())))
  650. if self.alpha == 0 and self.gamma == 0:
  651. args = printer._print(self.beta)
  652. s = stringPict('d' + ' '*pad)
  653. else:
  654. args = printer._print(self.alpha)
  655. args = prettyForm(*args.right(','))
  656. args = prettyForm(*args.right(printer._print(self.beta)))
  657. args = prettyForm(*args.right(','))
  658. args = prettyForm(*args.right(printer._print(self.gamma)))
  659. s = stringPict('D' + ' '*pad)
  660. args = prettyForm(*args.parens())
  661. s = prettyForm(*s.above(top))
  662. s = prettyForm(*s.below(bot))
  663. s = prettyForm(*s.right(args))
  664. return s
  665. def doit(self, **hints):
  666. hints['evaluate'] = True
  667. return WignerD(*self.args, **hints)
  668. def _eval_wignerd(self):
  669. j = sympify(self.j)
  670. m = sympify(self.m)
  671. mp = sympify(self.mp)
  672. alpha = sympify(self.alpha)
  673. beta = sympify(self.beta)
  674. gamma = sympify(self.gamma)
  675. if alpha == 0 and beta == 0 and gamma == 0:
  676. return KroneckerDelta(m, mp)
  677. if not j.is_number:
  678. raise ValueError(
  679. 'j parameter must be numerical to evaluate, got %s' % j)
  680. r = 0
  681. if beta == pi/2:
  682. # Varshalovich Equation (5), Section 4.16, page 113, setting
  683. # alpha=gamma=0.
  684. for k in range(2*j + 1):
  685. if k > j + mp or k > j - m or k < mp - m:
  686. continue
  687. r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
  688. r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
  689. factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
  690. else:
  691. # Varshalovich Equation(5), Section 4.7.2, page 87, where we set
  692. # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
  693. # then we use the Eq. (1), Section 4.4. page 79, to simplify:
  694. # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
  695. # This happens to be almost the same as in Eq.(10), Section 4.16,
  696. # except that we need to substitute -mp for mp.
  697. size, mvals = m_values(j)
  698. for mpp in mvals:
  699. r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
  700. Rotation.d(j, mpp, -mp, pi/2).doit()
  701. # Empirical normalization factor so results match Varshalovich
  702. # Tables 4.3-4.12
  703. # Note that this exact normalization does not follow from the
  704. # above equations
  705. r = r*I**(2*j - m - mp)*(-1)**(2*m)
  706. # Finally, simplify the whole expression
  707. r = simplify(r)
  708. r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
  709. return r
  710. Jx = JxOp('J')
  711. Jy = JyOp('J')
  712. Jz = JzOp('J')
  713. J2 = J2Op('J')
  714. Jplus = JplusOp('J')
  715. Jminus = JminusOp('J')
  716. #-----------------------------------------------------------------------------
  717. # Spin States
  718. #-----------------------------------------------------------------------------
  719. class SpinState(State):
  720. """Base class for angular momentum states."""
  721. _label_separator = ','
  722. def __new__(cls, j, m):
  723. j = sympify(j)
  724. m = sympify(m)
  725. if j.is_number:
  726. if 2*j != int(2*j):
  727. raise ValueError(
  728. 'j must be integer or half-integer, got: %s' % j)
  729. if j < 0:
  730. raise ValueError('j must be >= 0, got: %s' % j)
  731. if m.is_number:
  732. if 2*m != int(2*m):
  733. raise ValueError(
  734. 'm must be integer or half-integer, got: %s' % m)
  735. if j.is_number and m.is_number:
  736. if abs(m) > j:
  737. raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
  738. if int(j - m) != j - m:
  739. raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
  740. return State.__new__(cls, j, m)
  741. @property
  742. def j(self):
  743. return self.label[0]
  744. @property
  745. def m(self):
  746. return self.label[1]
  747. @classmethod
  748. def _eval_hilbert_space(cls, label):
  749. return ComplexSpace(2*label[0] + 1)
  750. def _represent_base(self, **options):
  751. j = self.j
  752. m = self.m
  753. alpha = sympify(options.get('alpha', 0))
  754. beta = sympify(options.get('beta', 0))
  755. gamma = sympify(options.get('gamma', 0))
  756. size, mvals = m_values(j)
  757. result = zeros(size, 1)
  758. # breaks finding angles on L930
  759. for p, mval in enumerate(mvals):
  760. if m.is_number:
  761. result[p, 0] = Rotation.D(
  762. self.j, mval, self.m, alpha, beta, gamma).doit()
  763. else:
  764. result[p, 0] = Rotation.D(self.j, mval,
  765. self.m, alpha, beta, gamma)
  766. return result
  767. def _eval_rewrite_as_Jx(self, *args, **options):
  768. if isinstance(self, Bra):
  769. return self._rewrite_basis(Jx, JxBra, **options)
  770. return self._rewrite_basis(Jx, JxKet, **options)
  771. def _eval_rewrite_as_Jy(self, *args, **options):
  772. if isinstance(self, Bra):
  773. return self._rewrite_basis(Jy, JyBra, **options)
  774. return self._rewrite_basis(Jy, JyKet, **options)
  775. def _eval_rewrite_as_Jz(self, *args, **options):
  776. if isinstance(self, Bra):
  777. return self._rewrite_basis(Jz, JzBra, **options)
  778. return self._rewrite_basis(Jz, JzKet, **options)
  779. def _rewrite_basis(self, basis, evect, **options):
  780. from sympy.physics.quantum.represent import represent
  781. j = self.j
  782. args = self.args[2:]
  783. if j.is_number:
  784. if isinstance(self, CoupledSpinState):
  785. if j == int(j):
  786. start = j**2
  787. else:
  788. start = (2*j - 1)*(2*j + 1)/4
  789. else:
  790. start = 0
  791. vect = represent(self, basis=basis, **options)
  792. result = Add(
  793. *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
  794. if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
  795. return uncouple(result)
  796. return result
  797. else:
  798. i = 0
  799. mi = symbols('mi')
  800. # make sure not to introduce a symbol already in the state
  801. while self.subs(mi, 0) != self:
  802. i += 1
  803. mi = symbols('mi%d' % i)
  804. break
  805. # TODO: better way to get angles of rotation
  806. if isinstance(self, CoupledSpinState):
  807. test_args = (0, mi, (0, 0))
  808. else:
  809. test_args = (0, mi)
  810. if isinstance(self, Ket):
  811. angles = represent(
  812. self.__class__(*test_args), basis=basis)[0].args[3:6]
  813. else:
  814. angles = represent(self.__class__(
  815. *test_args), basis=basis)[0].args[0].args[3:6]
  816. if angles == (0, 0, 0):
  817. return self
  818. else:
  819. state = evect(j, mi, *args)
  820. lt = Rotation.D(j, mi, self.m, *angles)
  821. return Sum(lt*state, (mi, -j, j))
  822. def _eval_innerproduct_JxBra(self, bra, **hints):
  823. result = KroneckerDelta(self.j, bra.j)
  824. if bra.dual_class() is not self.__class__:
  825. result *= self._represent_JxOp(None)[bra.j - bra.m]
  826. else:
  827. result *= KroneckerDelta(
  828. self.j, bra.j)*KroneckerDelta(self.m, bra.m)
  829. return result
  830. def _eval_innerproduct_JyBra(self, bra, **hints):
  831. result = KroneckerDelta(self.j, bra.j)
  832. if bra.dual_class() is not self.__class__:
  833. result *= self._represent_JyOp(None)[bra.j - bra.m]
  834. else:
  835. result *= KroneckerDelta(
  836. self.j, bra.j)*KroneckerDelta(self.m, bra.m)
  837. return result
  838. def _eval_innerproduct_JzBra(self, bra, **hints):
  839. result = KroneckerDelta(self.j, bra.j)
  840. if bra.dual_class() is not self.__class__:
  841. result *= self._represent_JzOp(None)[bra.j - bra.m]
  842. else:
  843. result *= KroneckerDelta(
  844. self.j, bra.j)*KroneckerDelta(self.m, bra.m)
  845. return result
  846. def _eval_trace(self, bra, **hints):
  847. # One way to implement this method is to assume the basis set k is
  848. # passed.
  849. # Then we can apply the discrete form of Trace formula here
  850. # Tr(|i><j| ) = \Sum_k <k|i><j|k>
  851. #then we do qapply() on each each inner product and sum over them.
  852. # OR
  853. # Inner product of |i><j| = Trace(Outer Product).
  854. # we could just use this unless there are cases when this is not true
  855. return (bra*self).doit()
  856. class JxKet(SpinState, Ket):
  857. """Eigenket of Jx.
  858. See JzKet for the usage of spin eigenstates.
  859. See Also
  860. ========
  861. JzKet: Usage of spin states
  862. """
  863. @classmethod
  864. def dual_class(self):
  865. return JxBra
  866. @classmethod
  867. def coupled_class(self):
  868. return JxKetCoupled
  869. def _represent_default_basis(self, **options):
  870. return self._represent_JxOp(None, **options)
  871. def _represent_JxOp(self, basis, **options):
  872. return self._represent_base(**options)
  873. def _represent_JyOp(self, basis, **options):
  874. return self._represent_base(alpha=pi*Rational(3, 2), **options)
  875. def _represent_JzOp(self, basis, **options):
  876. return self._represent_base(beta=pi/2, **options)
  877. class JxBra(SpinState, Bra):
  878. """Eigenbra of Jx.
  879. See JzKet for the usage of spin eigenstates.
  880. See Also
  881. ========
  882. JzKet: Usage of spin states
  883. """
  884. @classmethod
  885. def dual_class(self):
  886. return JxKet
  887. @classmethod
  888. def coupled_class(self):
  889. return JxBraCoupled
  890. class JyKet(SpinState, Ket):
  891. """Eigenket of Jy.
  892. See JzKet for the usage of spin eigenstates.
  893. See Also
  894. ========
  895. JzKet: Usage of spin states
  896. """
  897. @classmethod
  898. def dual_class(self):
  899. return JyBra
  900. @classmethod
  901. def coupled_class(self):
  902. return JyKetCoupled
  903. def _represent_default_basis(self, **options):
  904. return self._represent_JyOp(None, **options)
  905. def _represent_JxOp(self, basis, **options):
  906. return self._represent_base(gamma=pi/2, **options)
  907. def _represent_JyOp(self, basis, **options):
  908. return self._represent_base(**options)
  909. def _represent_JzOp(self, basis, **options):
  910. return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
  911. class JyBra(SpinState, Bra):
  912. """Eigenbra of Jy.
  913. See JzKet for the usage of spin eigenstates.
  914. See Also
  915. ========
  916. JzKet: Usage of spin states
  917. """
  918. @classmethod
  919. def dual_class(self):
  920. return JyKet
  921. @classmethod
  922. def coupled_class(self):
  923. return JyBraCoupled
  924. class JzKet(SpinState, Ket):
  925. """Eigenket of Jz.
  926. Spin state which is an eigenstate of the Jz operator. Uncoupled states,
  927. that is states representing the interaction of multiple separate spin
  928. states, are defined as a tensor product of states.
  929. Parameters
  930. ==========
  931. j : Number, Symbol
  932. Total spin angular momentum
  933. m : Number, Symbol
  934. Eigenvalue of the Jz spin operator
  935. Examples
  936. ========
  937. *Normal States:*
  938. Defining simple spin states, both numerical and symbolic:
  939. >>> from sympy.physics.quantum.spin import JzKet, JxKet
  940. >>> from sympy import symbols
  941. >>> JzKet(1, 0)
  942. |1,0>
  943. >>> j, m = symbols('j m')
  944. >>> JzKet(j, m)
  945. |j,m>
  946. Rewriting the JzKet in terms of eigenkets of the Jx operator:
  947. Note: that the resulting eigenstates are JxKet's
  948. >>> JzKet(1,1).rewrite("Jx")
  949. |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
  950. Get the vector representation of a state in terms of the basis elements
  951. of the Jx operator:
  952. >>> from sympy.physics.quantum.represent import represent
  953. >>> from sympy.physics.quantum.spin import Jx, Jz
  954. >>> represent(JzKet(1,-1), basis=Jx)
  955. Matrix([
  956. [ 1/2],
  957. [sqrt(2)/2],
  958. [ 1/2]])
  959. Apply innerproducts between states:
  960. >>> from sympy.physics.quantum.innerproduct import InnerProduct
  961. >>> from sympy.physics.quantum.spin import JxBra
  962. >>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
  963. >>> i
  964. <1,1|1,1>
  965. >>> i.doit()
  966. 1/2
  967. *Uncoupled States:*
  968. Define an uncoupled state as a TensorProduct between two Jz eigenkets:
  969. >>> from sympy.physics.quantum.tensorproduct import TensorProduct
  970. >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
  971. >>> TensorProduct(JzKet(1,0), JzKet(1,1))
  972. |1,0>x|1,1>
  973. >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
  974. |j1,m1>x|j2,m2>
  975. A TensorProduct can be rewritten, in which case the eigenstates that make
  976. up the tensor product is rewritten to the new basis:
  977. >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
  978. |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
  979. The represent method for TensorProduct's gives the vector representation of
  980. the state. Note that the state in the product basis is the equivalent of the
  981. tensor product of the vector representation of the component eigenstates:
  982. >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
  983. Matrix([
  984. [0],
  985. [0],
  986. [0],
  987. [1],
  988. [0],
  989. [0],
  990. [0],
  991. [0],
  992. [0]])
  993. >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
  994. Matrix([
  995. [ 1/2],
  996. [sqrt(2)/2],
  997. [ 1/2],
  998. [ 0],
  999. [ 0],
  1000. [ 0],
  1001. [ 0],
  1002. [ 0],
  1003. [ 0]])
  1004. See Also
  1005. ========
  1006. JzKetCoupled: Coupled eigenstates
  1007. sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
  1008. uncouple: Uncouples states given coupling parameters
  1009. couple: Couples uncoupled states
  1010. """
  1011. @classmethod
  1012. def dual_class(self):
  1013. return JzBra
  1014. @classmethod
  1015. def coupled_class(self):
  1016. return JzKetCoupled
  1017. def _represent_default_basis(self, **options):
  1018. return self._represent_JzOp(None, **options)
  1019. def _represent_JxOp(self, basis, **options):
  1020. return self._represent_base(beta=pi*Rational(3, 2), **options)
  1021. def _represent_JyOp(self, basis, **options):
  1022. return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
  1023. def _represent_JzOp(self, basis, **options):
  1024. return self._represent_base(**options)
  1025. class JzBra(SpinState, Bra):
  1026. """Eigenbra of Jz.
  1027. See the JzKet for the usage of spin eigenstates.
  1028. See Also
  1029. ========
  1030. JzKet: Usage of spin states
  1031. """
  1032. @classmethod
  1033. def dual_class(self):
  1034. return JzKet
  1035. @classmethod
  1036. def coupled_class(self):
  1037. return JzBraCoupled
  1038. # Method used primarily to create coupled_n and coupled_jn by __new__ in
  1039. # CoupledSpinState
  1040. # This same method is also used by the uncouple method, and is separated from
  1041. # the CoupledSpinState class to maintain consistency in defining coupling
  1042. def _build_coupled(jcoupling, length):
  1043. n_list = [ [n + 1] for n in range(length) ]
  1044. coupled_jn = []
  1045. coupled_n = []
  1046. for n1, n2, j_new in jcoupling:
  1047. coupled_jn.append(j_new)
  1048. coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
  1049. n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
  1050. n_list[n_sort[0] - 1] = n_sort
  1051. return coupled_n, coupled_jn
  1052. class CoupledSpinState(SpinState):
  1053. """Base class for coupled angular momentum states."""
  1054. def __new__(cls, j, m, jn, *jcoupling):
  1055. # Check j and m values using SpinState
  1056. SpinState(j, m)
  1057. # Build and check coupling scheme from arguments
  1058. if len(jcoupling) == 0:
  1059. # Use default coupling scheme
  1060. jcoupling = []
  1061. for n in range(2, len(jn)):
  1062. jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
  1063. jcoupling.append( (1, len(jn), j) )
  1064. elif len(jcoupling) == 1:
  1065. # Use specified coupling scheme
  1066. jcoupling = jcoupling[0]
  1067. else:
  1068. raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
  1069. # Check arguments have correct form
  1070. if not isinstance(jn, (list, tuple, Tuple)):
  1071. raise TypeError('jn must be Tuple, list or tuple, got %s' %
  1072. jn.__class__.__name__)
  1073. if not isinstance(jcoupling, (list, tuple, Tuple)):
  1074. raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
  1075. jcoupling.__class__.__name__)
  1076. if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
  1077. raise TypeError(
  1078. 'All elements of jcoupling must be list, tuple or Tuple')
  1079. if not len(jn) - 1 == len(jcoupling):
  1080. raise ValueError('jcoupling must have length of %d, got %d' %
  1081. (len(jn) - 1, len(jcoupling)))
  1082. if not all(len(x) == 3 for x in jcoupling):
  1083. raise ValueError('All elements of jcoupling must have length 3')
  1084. # Build sympified args
  1085. j = sympify(j)
  1086. m = sympify(m)
  1087. jn = Tuple( *[sympify(ji) for ji in jn] )
  1088. jcoupling = Tuple( *[Tuple(sympify(
  1089. n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
  1090. # Check values in coupling scheme give physical state
  1091. if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
  1092. raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
  1093. if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
  1094. raise ValueError('Indices in jcoupling must be integers')
  1095. if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
  1096. raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
  1097. if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
  1098. raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
  1099. coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
  1100. jvals = list(jn)
  1101. for n, (n1, n2) in enumerate(coupled_n):
  1102. j1 = jvals[min(n1) - 1]
  1103. j2 = jvals[min(n2) - 1]
  1104. j3 = coupled_jn[n]
  1105. if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
  1106. if j1 + j2 < j3:
  1107. raise ValueError('All couplings must have j1+j2 >= j3, '
  1108. 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
  1109. if abs(j1 - j2) > j3:
  1110. raise ValueError("All couplings must have |j1+j2| <= j3, "
  1111. "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
  1112. if int(j1 + j2) == j1 + j2:
  1113. pass
  1114. jvals[min(n1 + n2) - 1] = j3
  1115. if len(jcoupling) > 0 and jcoupling[-1][2] != j:
  1116. raise ValueError('Last j value coupled together must be the final j of the state')
  1117. # Return state
  1118. return State.__new__(cls, j, m, jn, jcoupling)
  1119. def _print_label(self, printer, *args):
  1120. label = [printer._print(self.j), printer._print(self.m)]
  1121. for i, ji in enumerate(self.jn, start=1):
  1122. label.append('j%d=%s' % (
  1123. i, printer._print(ji)
  1124. ))
  1125. for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
  1126. label.append('j(%s)=%s' % (
  1127. ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
  1128. ))
  1129. return ','.join(label)
  1130. def _print_label_pretty(self, printer, *args):
  1131. label = [self.j, self.m]
  1132. for i, ji in enumerate(self.jn, start=1):
  1133. symb = 'j%d' % i
  1134. symb = pretty_symbol(symb)
  1135. symb = prettyForm(symb + '=')
  1136. item = prettyForm(*symb.right(printer._print(ji)))
  1137. label.append(item)
  1138. for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
  1139. n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
  1140. symb = prettyForm('j' + n + '=')
  1141. item = prettyForm(*symb.right(printer._print(jn)))
  1142. label.append(item)
  1143. return self._print_sequence_pretty(
  1144. label, self._label_separator, printer, *args
  1145. )
  1146. def _print_label_latex(self, printer, *args):
  1147. label = [
  1148. printer._print(self.j, *args),
  1149. printer._print(self.m, *args)
  1150. ]
  1151. for i, ji in enumerate(self.jn, start=1):
  1152. label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
  1153. for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
  1154. n = ','.join(str(i) for i in sorted(n1 + n2))
  1155. label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
  1156. return self._label_separator.join(label)
  1157. @property
  1158. def jn(self):
  1159. return self.label[2]
  1160. @property
  1161. def coupling(self):
  1162. return self.label[3]
  1163. @property
  1164. def coupled_jn(self):
  1165. return _build_coupled(self.label[3], len(self.label[2]))[1]
  1166. @property
  1167. def coupled_n(self):
  1168. return _build_coupled(self.label[3], len(self.label[2]))[0]
  1169. @classmethod
  1170. def _eval_hilbert_space(cls, label):
  1171. j = Add(*label[2])
  1172. if j.is_number:
  1173. return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
  1174. else:
  1175. # TODO: Need hilbert space fix, see issue 5732
  1176. # Desired behavior:
  1177. #ji = symbols('ji')
  1178. #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
  1179. # Temporary fix:
  1180. return ComplexSpace(2*j + 1)
  1181. def _represent_coupled_base(self, **options):
  1182. evect = self.uncoupled_class()
  1183. if not self.j.is_number:
  1184. raise ValueError(
  1185. 'State must not have symbolic j value to represent')
  1186. if not self.hilbert_space.dimension.is_number:
  1187. raise ValueError(
  1188. 'State must not have symbolic j values to represent')
  1189. result = zeros(self.hilbert_space.dimension, 1)
  1190. if self.j == int(self.j):
  1191. start = self.j**2
  1192. else:
  1193. start = (2*self.j - 1)*(1 + 2*self.j)/4
  1194. result[start:start + 2*self.j + 1, 0] = evect(
  1195. self.j, self.m)._represent_base(**options)
  1196. return result
  1197. def _eval_rewrite_as_Jx(self, *args, **options):
  1198. if isinstance(self, Bra):
  1199. return self._rewrite_basis(Jx, JxBraCoupled, **options)
  1200. return self._rewrite_basis(Jx, JxKetCoupled, **options)
  1201. def _eval_rewrite_as_Jy(self, *args, **options):
  1202. if isinstance(self, Bra):
  1203. return self._rewrite_basis(Jy, JyBraCoupled, **options)
  1204. return self._rewrite_basis(Jy, JyKetCoupled, **options)
  1205. def _eval_rewrite_as_Jz(self, *args, **options):
  1206. if isinstance(self, Bra):
  1207. return self._rewrite_basis(Jz, JzBraCoupled, **options)
  1208. return self._rewrite_basis(Jz, JzKetCoupled, **options)
  1209. class JxKetCoupled(CoupledSpinState, Ket):
  1210. """Coupled eigenket of Jx.
  1211. See JzKetCoupled for the usage of coupled spin eigenstates.
  1212. See Also
  1213. ========
  1214. JzKetCoupled: Usage of coupled spin states
  1215. """
  1216. @classmethod
  1217. def dual_class(self):
  1218. return JxBraCoupled
  1219. @classmethod
  1220. def uncoupled_class(self):
  1221. return JxKet
  1222. def _represent_default_basis(self, **options):
  1223. return self._represent_JzOp(None, **options)
  1224. def _represent_JxOp(self, basis, **options):
  1225. return self._represent_coupled_base(**options)
  1226. def _represent_JyOp(self, basis, **options):
  1227. return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
  1228. def _represent_JzOp(self, basis, **options):
  1229. return self._represent_coupled_base(beta=pi/2, **options)
  1230. class JxBraCoupled(CoupledSpinState, Bra):
  1231. """Coupled eigenbra of Jx.
  1232. See JzKetCoupled for the usage of coupled spin eigenstates.
  1233. See Also
  1234. ========
  1235. JzKetCoupled: Usage of coupled spin states
  1236. """
  1237. @classmethod
  1238. def dual_class(self):
  1239. return JxKetCoupled
  1240. @classmethod
  1241. def uncoupled_class(self):
  1242. return JxBra
  1243. class JyKetCoupled(CoupledSpinState, Ket):
  1244. """Coupled eigenket of Jy.
  1245. See JzKetCoupled for the usage of coupled spin eigenstates.
  1246. See Also
  1247. ========
  1248. JzKetCoupled: Usage of coupled spin states
  1249. """
  1250. @classmethod
  1251. def dual_class(self):
  1252. return JyBraCoupled
  1253. @classmethod
  1254. def uncoupled_class(self):
  1255. return JyKet
  1256. def _represent_default_basis(self, **options):
  1257. return self._represent_JzOp(None, **options)
  1258. def _represent_JxOp(self, basis, **options):
  1259. return self._represent_coupled_base(gamma=pi/2, **options)
  1260. def _represent_JyOp(self, basis, **options):
  1261. return self._represent_coupled_base(**options)
  1262. def _represent_JzOp(self, basis, **options):
  1263. return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
  1264. class JyBraCoupled(CoupledSpinState, Bra):
  1265. """Coupled eigenbra of Jy.
  1266. See JzKetCoupled for the usage of coupled spin eigenstates.
  1267. See Also
  1268. ========
  1269. JzKetCoupled: Usage of coupled spin states
  1270. """
  1271. @classmethod
  1272. def dual_class(self):
  1273. return JyKetCoupled
  1274. @classmethod
  1275. def uncoupled_class(self):
  1276. return JyBra
  1277. class JzKetCoupled(CoupledSpinState, Ket):
  1278. r"""Coupled eigenket of Jz
  1279. Spin state that is an eigenket of Jz which represents the coupling of
  1280. separate spin spaces.
  1281. The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
  1282. ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
  1283. are the total angular momentum quantum numbers, as used for normal states
  1284. (e.g. JzKet).
  1285. The other required parameter in ``jn``, which is a tuple defining the `j_n`
  1286. angular momentum quantum numbers of the product spaces. So for example, if
  1287. a state represented the coupling of the product basis state
  1288. `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
  1289. for this state would be ``(j1,j2)``.
  1290. The final option is ``jcoupling``, which is used to define how the spaces
  1291. specified by ``jn`` are coupled, which includes both the order these spaces
  1292. are coupled together and the quantum numbers that arise from these
  1293. couplings. The ``jcoupling`` parameter itself is a list of lists, such that
  1294. each of the sublists defines a single coupling between the spin spaces. If
  1295. there are N coupled angular momentum spaces, that is ``jn`` has N elements,
  1296. then there must be N-1 sublists. Each of these sublists making up the
  1297. ``jcoupling`` parameter have length 3. The first two elements are the
  1298. indices of the product spaces that are considered to be coupled together.
  1299. For example, if we want to couple `j_1` and `j_4`, the indices would be 1
  1300. and 4. If a state has already been coupled, it is referenced by the
  1301. smallest index that is coupled, so if `j_2` and `j_4` has already been
  1302. coupled to some `j_{24}`, then this value can be coupled by referencing it
  1303. with index 2. The final element of the sublist is the quantum number of the
  1304. coupled state. So putting everything together, into a valid sublist for
  1305. ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
  1306. with quantum number `j_{12}` with the value ``j12``, the sublist would be
  1307. ``(1,2,j12)``, N-1 of these sublists are used in the list for
  1308. ``jcoupling``.
  1309. Note the ``jcoupling`` parameter is optional, if it is not specified, the
  1310. default coupling is taken. This default value is to coupled the spaces in
  1311. order and take the quantum number of the coupling to be the maximum value.
  1312. For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
  1313. default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
  1314. `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
  1315. `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
  1316. correspond to this is:
  1317. ``((1,2,j1+j2),(1,3,j1+j2+j3))``
  1318. Parameters
  1319. ==========
  1320. args : tuple
  1321. The arguments that must be passed are ``j``, ``m``, ``jn``, and
  1322. ``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
  1323. value is the eigenvalue of the Jz spin operator. The ``jn`` list are
  1324. the j values of argular momentum spaces coupled together. The
  1325. ``jcoupling`` parameter is an optional parameter defining how the spaces
  1326. are coupled together. See the above description for how these coupling
  1327. parameters are defined.
  1328. Examples
  1329. ========
  1330. Defining simple spin states, both numerical and symbolic:
  1331. >>> from sympy.physics.quantum.spin import JzKetCoupled
  1332. >>> from sympy import symbols
  1333. >>> JzKetCoupled(1, 0, (1, 1))
  1334. |1,0,j1=1,j2=1>
  1335. >>> j, m, j1, j2 = symbols('j m j1 j2')
  1336. >>> JzKetCoupled(j, m, (j1, j2))
  1337. |j,m,j1=j1,j2=j2>
  1338. Defining coupled spin states for more than 2 coupled spaces with various
  1339. coupling parameters:
  1340. >>> JzKetCoupled(2, 1, (1, 1, 1))
  1341. |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
  1342. >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
  1343. |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
  1344. >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
  1345. |2,1,j1=1,j2=1,j3=1,j(2,3)=1>
  1346. Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
  1347. Note: that the resulting eigenstates are JxKetCoupled
  1348. >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
  1349. |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
  1350. The rewrite method can be used to convert a coupled state to an uncoupled
  1351. state. This is done by passing coupled=False to the rewrite function:
  1352. >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
  1353. -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
  1354. Get the vector representation of a state in terms of the basis elements
  1355. of the Jx operator:
  1356. >>> from sympy.physics.quantum.represent import represent
  1357. >>> from sympy.physics.quantum.spin import Jx
  1358. >>> from sympy import S
  1359. >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
  1360. Matrix([
  1361. [ 0],
  1362. [ 1/2],
  1363. [sqrt(2)/2],
  1364. [ 1/2]])
  1365. See Also
  1366. ========
  1367. JzKet: Normal spin eigenstates
  1368. uncouple: Uncoupling of coupling spin states
  1369. couple: Coupling of uncoupled spin states
  1370. """
  1371. @classmethod
  1372. def dual_class(self):
  1373. return JzBraCoupled
  1374. @classmethod
  1375. def uncoupled_class(self):
  1376. return JzKet
  1377. def _represent_default_basis(self, **options):
  1378. return self._represent_JzOp(None, **options)
  1379. def _represent_JxOp(self, basis, **options):
  1380. return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
  1381. def _represent_JyOp(self, basis, **options):
  1382. return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
  1383. def _represent_JzOp(self, basis, **options):
  1384. return self._represent_coupled_base(**options)
  1385. class JzBraCoupled(CoupledSpinState, Bra):
  1386. """Coupled eigenbra of Jz.
  1387. See the JzKetCoupled for the usage of coupled spin eigenstates.
  1388. See Also
  1389. ========
  1390. JzKetCoupled: Usage of coupled spin states
  1391. """
  1392. @classmethod
  1393. def dual_class(self):
  1394. return JzKetCoupled
  1395. @classmethod
  1396. def uncoupled_class(self):
  1397. return JzBra
  1398. #-----------------------------------------------------------------------------
  1399. # Coupling/uncoupling
  1400. #-----------------------------------------------------------------------------
  1401. def couple(expr, jcoupling_list=None):
  1402. """ Couple a tensor product of spin states
  1403. This function can be used to couple an uncoupled tensor product of spin
  1404. states. All of the eigenstates to be coupled must be of the same class. It
  1405. will return a linear combination of eigenstates that are subclasses of
  1406. CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
  1407. coefficients.
  1408. Parameters
  1409. ==========
  1410. expr : Expr
  1411. An expression involving TensorProducts of spin states to be coupled.
  1412. Each state must be a subclass of SpinState and they all must be the
  1413. same class.
  1414. jcoupling_list : list or tuple
  1415. Elements of this list are sub-lists of length 2 specifying the order of
  1416. the coupling of the spin spaces. The length of this must be N-1, where N
  1417. is the number of states in the tensor product to be coupled. The
  1418. elements of this sublist are the same as the first two elements of each
  1419. sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
  1420. parameter is not specified, the default value is taken, which couples
  1421. the first and second product basis spaces, then couples this new coupled
  1422. space to the third product space, etc
  1423. Examples
  1424. ========
  1425. Couple a tensor product of numerical states for two spaces:
  1426. >>> from sympy.physics.quantum.spin import JzKet, couple
  1427. >>> from sympy.physics.quantum.tensorproduct import TensorProduct
  1428. >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
  1429. -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
  1430. Numerical coupling of three spaces using the default coupling method, i.e.
  1431. first and second spaces couple, then this couples to the third space:
  1432. >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
  1433. sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
  1434. Perform this same coupling, but we define the coupling to first couple
  1435. the first and third spaces:
  1436. >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
  1437. sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
  1438. Couple a tensor product of symbolic states:
  1439. >>> from sympy import symbols
  1440. >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
  1441. >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
  1442. Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
  1443. """
  1444. a = expr.atoms(TensorProduct)
  1445. for tp in a:
  1446. # Allow other tensor products to be in expression
  1447. if not all(isinstance(state, SpinState) for state in tp.args):
  1448. continue
  1449. # If tensor product has all spin states, raise error for invalid tensor product state
  1450. if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
  1451. raise TypeError('All states must be the same basis')
  1452. expr = expr.subs(tp, _couple(tp, jcoupling_list))
  1453. return expr
  1454. def _couple(tp, jcoupling_list):
  1455. states = tp.args
  1456. coupled_evect = states[0].coupled_class()
  1457. # Define default coupling if none is specified
  1458. if jcoupling_list is None:
  1459. jcoupling_list = []
  1460. for n in range(1, len(states)):
  1461. jcoupling_list.append( (1, n + 1) )
  1462. # Check jcoupling_list valid
  1463. if not len(jcoupling_list) == len(states) - 1:
  1464. raise TypeError('jcoupling_list must be length %d, got %d' %
  1465. (len(states) - 1, len(jcoupling_list)))
  1466. if not all( len(coupling) == 2 for coupling in jcoupling_list):
  1467. raise ValueError('Each coupling must define 2 spaces')
  1468. if any(n1 == n2 for n1, n2 in jcoupling_list):
  1469. raise ValueError('Spin spaces cannot couple to themselves')
  1470. if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
  1471. j_test = [0]*len(states)
  1472. for n1, n2 in jcoupling_list:
  1473. if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
  1474. raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
  1475. j_test[max(n1, n2) - 1] = -1
  1476. # j values of states to be coupled together
  1477. jn = [state.j for state in states]
  1478. mn = [state.m for state in states]
  1479. # Create coupling_list, which defines all the couplings between all
  1480. # the spaces from jcoupling_list
  1481. coupling_list = []
  1482. n_list = [ [i + 1] for i in range(len(states)) ]
  1483. for j_coupling in jcoupling_list:
  1484. # Least n for all j_n which is coupled as first and second spaces
  1485. n1, n2 = j_coupling
  1486. # List of all n's coupled in first and second spaces
  1487. j1_n = list(n_list[n1 - 1])
  1488. j2_n = list(n_list[n2 - 1])
  1489. coupling_list.append( (j1_n, j2_n) )
  1490. # Set new j_n to be coupling of all j_n in both first and second spaces
  1491. n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
  1492. if all(state.j.is_number and state.m.is_number for state in states):
  1493. # Numerical coupling
  1494. # Iterate over difference between maximum possible j value of each coupling and the actual value
  1495. diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
  1496. coupling[1] ] ) for coupling in coupling_list ]
  1497. result = []
  1498. for diff in range(diff_max[-1] + 1):
  1499. # Determine available configurations
  1500. n = len(coupling_list)
  1501. tot = binomial(diff + n - 1, diff)
  1502. for config_num in range(tot):
  1503. diff_list = _confignum_to_difflist(config_num, diff, n)
  1504. # Skip the configuration if non-physical
  1505. # This is a lazy check for physical states given the loose restrictions of diff_max
  1506. if any(d > m for d, m in zip(diff_list, diff_max)):
  1507. continue
  1508. # Determine term
  1509. cg_terms = []
  1510. coupled_j = list(jn)
  1511. jcoupling = []
  1512. for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
  1513. j1 = coupled_j[ min(j1_n) - 1 ]
  1514. j2 = coupled_j[ min(j2_n) - 1 ]
  1515. j3 = j1 + j2 - coupling_diff
  1516. coupled_j[ min(j1_n + j2_n) - 1 ] = j3
  1517. m1 = Add( *[ mn[x - 1] for x in j1_n] )
  1518. m2 = Add( *[ mn[x - 1] for x in j2_n] )
  1519. m3 = m1 + m2
  1520. cg_terms.append( (j1, m1, j2, m2, j3, m3) )
  1521. jcoupling.append( (min(j1_n), min(j2_n), j3) )
  1522. # Better checks that state is physical
  1523. if any(abs(term[5]) > term[4] for term in cg_terms):
  1524. continue
  1525. if any(term[0] + term[2] < term[4] for term in cg_terms):
  1526. continue
  1527. if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
  1528. continue
  1529. coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
  1530. state = coupled_evect(j3, m3, jn, jcoupling)
  1531. result.append(coeff*state)
  1532. return Add(*result)
  1533. else:
  1534. # Symbolic coupling
  1535. cg_terms = []
  1536. jcoupling = []
  1537. sum_terms = []
  1538. coupled_j = list(jn)
  1539. for j1_n, j2_n in coupling_list:
  1540. j1 = coupled_j[ min(j1_n) - 1 ]
  1541. j2 = coupled_j[ min(j2_n) - 1 ]
  1542. if len(j1_n + j2_n) == len(states):
  1543. j3 = symbols('j')
  1544. else:
  1545. j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
  1546. j3 = symbols(j3_name)
  1547. coupled_j[ min(j1_n + j2_n) - 1 ] = j3
  1548. m1 = Add( *[ mn[x - 1] for x in j1_n] )
  1549. m2 = Add( *[ mn[x - 1] for x in j2_n] )
  1550. m3 = m1 + m2
  1551. cg_terms.append( (j1, m1, j2, m2, j3, m3) )
  1552. jcoupling.append( (min(j1_n), min(j2_n), j3) )
  1553. sum_terms.append((j3, m3, j1 + j2))
  1554. coeff = Mul( *[ CG(*term) for term in cg_terms] )
  1555. state = coupled_evect(j3, m3, jn, jcoupling)
  1556. return Sum(coeff*state, *sum_terms)
  1557. def uncouple(expr, jn=None, jcoupling_list=None):
  1558. """ Uncouple a coupled spin state
  1559. Gives the uncoupled representation of a coupled spin state. Arguments must
  1560. be either a spin state that is a subclass of CoupledSpinState or a spin
  1561. state that is a subclass of SpinState and an array giving the j values
  1562. of the spaces that are to be coupled
  1563. Parameters
  1564. ==========
  1565. expr : Expr
  1566. The expression containing states that are to be coupled. If the states
  1567. are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
  1568. must be defined. If the states are a subclass of CoupledSpinState,
  1569. ``jn`` and ``jcoupling`` will be taken from the state.
  1570. jn : list or tuple
  1571. The list of the j-values that are coupled. If state is a
  1572. CoupledSpinState, this parameter is ignored. This must be defined if
  1573. state is not a subclass of CoupledSpinState. The syntax of this
  1574. parameter is the same as the ``jn`` parameter of JzKetCoupled.
  1575. jcoupling_list : list or tuple
  1576. The list defining how the j-values are coupled together. If state is a
  1577. CoupledSpinState, this parameter is ignored. This must be defined if
  1578. state is not a subclass of CoupledSpinState. The syntax of this
  1579. parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
  1580. Examples
  1581. ========
  1582. Uncouple a numerical state using a CoupledSpinState state:
  1583. >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
  1584. >>> from sympy import S
  1585. >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
  1586. sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
  1587. Perform the same calculation using a SpinState state:
  1588. >>> from sympy.physics.quantum.spin import JzKet
  1589. >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
  1590. sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
  1591. Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
  1592. >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
  1593. |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
  1594. Perform the same calculation using a SpinState state:
  1595. >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
  1596. |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
  1597. Uncouple a symbolic state using a CoupledSpinState state:
  1598. >>> from sympy import symbols
  1599. >>> j,m,j1,j2 = symbols('j m j1 j2')
  1600. >>> uncouple(JzKetCoupled(j, m, (j1, j2)))
  1601. Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
  1602. Perform the same calculation using a SpinState state
  1603. >>> uncouple(JzKet(j, m), (j1, j2))
  1604. Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
  1605. """
  1606. a = expr.atoms(SpinState)
  1607. for state in a:
  1608. expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
  1609. return expr
  1610. def _uncouple(state, jn, jcoupling_list):
  1611. if isinstance(state, CoupledSpinState):
  1612. jn = state.jn
  1613. coupled_n = state.coupled_n
  1614. coupled_jn = state.coupled_jn
  1615. evect = state.uncoupled_class()
  1616. elif isinstance(state, SpinState):
  1617. if jn is None:
  1618. raise ValueError("Must specify j-values for coupled state")
  1619. if not isinstance(jn, (list, tuple)):
  1620. raise TypeError("jn must be list or tuple")
  1621. if jcoupling_list is None:
  1622. # Use default
  1623. jcoupling_list = []
  1624. for i in range(1, len(jn)):
  1625. jcoupling_list.append(
  1626. (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
  1627. if not isinstance(jcoupling_list, (list, tuple)):
  1628. raise TypeError("jcoupling must be a list or tuple")
  1629. if not len(jcoupling_list) == len(jn) - 1:
  1630. raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
  1631. coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
  1632. evect = state.__class__
  1633. else:
  1634. raise TypeError("state must be a spin state")
  1635. j = state.j
  1636. m = state.m
  1637. coupling_list = []
  1638. j_list = list(jn)
  1639. # Create coupling, which defines all the couplings between all the spaces
  1640. for j3, (n1, n2) in zip(coupled_jn, coupled_n):
  1641. # j's which are coupled as first and second spaces
  1642. j1 = j_list[n1[0] - 1]
  1643. j2 = j_list[n2[0] - 1]
  1644. # Build coupling list
  1645. coupling_list.append( (n1, n2, j1, j2, j3) )
  1646. # Set new value in j_list
  1647. j_list[min(n1 + n2) - 1] = j3
  1648. if j.is_number and m.is_number:
  1649. diff_max = [ 2*x for x in jn ]
  1650. diff = Add(*jn) - m
  1651. n = len(jn)
  1652. tot = binomial(diff + n - 1, diff)
  1653. result = []
  1654. for config_num in range(tot):
  1655. diff_list = _confignum_to_difflist(config_num, diff, n)
  1656. if any(d > p for d, p in zip(diff_list, diff_max)):
  1657. continue
  1658. cg_terms = []
  1659. for coupling in coupling_list:
  1660. j1_n, j2_n, j1, j2, j3 = coupling
  1661. m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
  1662. m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
  1663. m3 = m1 + m2
  1664. cg_terms.append( (j1, m1, j2, m2, j3, m3) )
  1665. coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
  1666. state = TensorProduct(
  1667. *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
  1668. result.append(coeff*state)
  1669. return Add(*result)
  1670. else:
  1671. # Symbolic coupling
  1672. m_str = "m1:%d" % (len(jn) + 1)
  1673. mvals = symbols(m_str)
  1674. cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
  1675. j2, Add(*[mvals[n - 1] for n in j2_n]),
  1676. j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
  1677. cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
  1678. j2, Add(*[mvals[n - 1] for n in j2_n]),
  1679. j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
  1680. cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
  1681. sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
  1682. state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
  1683. return Sum(cg_coeff*state, *sum_terms)
  1684. def _confignum_to_difflist(config_num, diff, list_len):
  1685. # Determines configuration of diffs into list_len number of slots
  1686. diff_list = []
  1687. for n in range(list_len):
  1688. prev_diff = diff
  1689. # Number of spots after current one
  1690. rem_spots = list_len - n - 1
  1691. # Number of configurations of distributing diff among the remaining spots
  1692. rem_configs = binomial(diff + rem_spots - 1, diff)
  1693. while config_num >= rem_configs:
  1694. config_num -= rem_configs
  1695. diff -= 1
  1696. rem_configs = binomial(diff + rem_spots - 1, diff)
  1697. diff_list.append(prev_diff - diff)
  1698. return diff_list