gamma_matrices.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. """
  2. Module to handle gamma matrices expressed as tensor objects.
  3. Examples
  4. ========
  5. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
  6. >>> from sympy.tensor.tensor import tensor_indices
  7. >>> i = tensor_indices('i', LorentzIndex)
  8. >>> G(i)
  9. GammaMatrix(i)
  10. Note that there is already an instance of GammaMatrixHead in four dimensions:
  11. GammaMatrix, which is simply declare as
  12. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix
  13. >>> from sympy.tensor.tensor import tensor_indices
  14. >>> i = tensor_indices('i', LorentzIndex)
  15. >>> GammaMatrix(i)
  16. GammaMatrix(i)
  17. To access the metric tensor
  18. >>> LorentzIndex.metric
  19. metric(LorentzIndex,LorentzIndex)
  20. """
  21. from sympy.core.mul import Mul
  22. from sympy.core.singleton import S
  23. from sympy.matrices.dense import eye
  24. from sympy.matrices.expressions.trace import trace
  25. from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
  26. TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
  27. # DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
  28. LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
  29. GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
  30. TensorSymmetry.no_symmetry(1), comm=None)
  31. def extract_type_tens(expression, component):
  32. """
  33. Extract from a ``TensExpr`` all tensors with `component`.
  34. Returns two tensor expressions:
  35. * the first contains all ``Tensor`` of having `component`.
  36. * the second contains all remaining.
  37. """
  38. if isinstance(expression, Tensor):
  39. sp = [expression]
  40. elif isinstance(expression, TensMul):
  41. sp = expression.args
  42. else:
  43. raise ValueError('wrong type')
  44. # Collect all gamma matrices of the same dimension
  45. new_expr = S.One
  46. residual_expr = S.One
  47. for i in sp:
  48. if isinstance(i, Tensor) and i.component == component:
  49. new_expr *= i
  50. else:
  51. residual_expr *= i
  52. return new_expr, residual_expr
  53. def simplify_gamma_expression(expression):
  54. extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
  55. res_expr = _simplify_single_line(extracted_expr)
  56. return res_expr * residual_expr
  57. def simplify_gpgp(ex, sort=True):
  58. """
  59. simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
  60. Examples
  61. ========
  62. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
  63. LorentzIndex, simplify_gpgp
  64. >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
  65. >>> p, q = tensor_heads('p, q', [LorentzIndex])
  66. >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
  67. >>> ps = p(i0)*G(-i0)
  68. >>> qs = q(i0)*G(-i0)
  69. >>> simplify_gpgp(ps*qs*qs)
  70. GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
  71. """
  72. def _simplify_gpgp(ex):
  73. components = ex.components
  74. a = []
  75. comp_map = []
  76. for i, comp in enumerate(components):
  77. comp_map.extend([i]*comp.rank)
  78. dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
  79. for i in range(len(components)):
  80. if components[i] != GammaMatrix:
  81. continue
  82. for dx in dum:
  83. if dx[2] == i:
  84. p_pos1 = dx[3]
  85. elif dx[3] == i:
  86. p_pos1 = dx[2]
  87. else:
  88. continue
  89. comp1 = components[p_pos1]
  90. if comp1.comm == 0 and comp1.rank == 1:
  91. a.append((i, p_pos1))
  92. if not a:
  93. return ex
  94. elim = set()
  95. tv = []
  96. hit = True
  97. coeff = S.One
  98. ta = None
  99. while hit:
  100. hit = False
  101. for i, ai in enumerate(a[:-1]):
  102. if ai[0] in elim:
  103. continue
  104. if ai[0] != a[i + 1][0] - 1:
  105. continue
  106. if components[ai[1]] != components[a[i + 1][1]]:
  107. continue
  108. elim.add(ai[0])
  109. elim.add(ai[1])
  110. elim.add(a[i + 1][0])
  111. elim.add(a[i + 1][1])
  112. if not ta:
  113. ta = ex.split()
  114. mu = TensorIndex('mu', LorentzIndex)
  115. hit = True
  116. if i == 0:
  117. coeff = ex.coeff
  118. tx = components[ai[1]](mu)*components[ai[1]](-mu)
  119. if len(a) == 2:
  120. tx *= 4 # eye(4)
  121. tv.append(tx)
  122. break
  123. if tv:
  124. a = [x for j, x in enumerate(ta) if j not in elim]
  125. a.extend(tv)
  126. t = tensor_mul(*a)*coeff
  127. # t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
  128. return t
  129. else:
  130. return ex
  131. if sort:
  132. ex = ex.sorted_components()
  133. # this would be better off with pattern matching
  134. while 1:
  135. t = _simplify_gpgp(ex)
  136. if t != ex:
  137. ex = t
  138. else:
  139. return t
  140. def gamma_trace(t):
  141. """
  142. trace of a single line of gamma matrices
  143. Examples
  144. ========
  145. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
  146. gamma_trace, LorentzIndex
  147. >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
  148. >>> p, q = tensor_heads('p, q', [LorentzIndex])
  149. >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
  150. >>> ps = p(i0)*G(-i0)
  151. >>> qs = q(i0)*G(-i0)
  152. >>> gamma_trace(G(i0)*G(i1))
  153. 4*metric(i0, i1)
  154. >>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
  155. 0
  156. >>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
  157. 0
  158. """
  159. if isinstance(t, TensAdd):
  160. res = TensAdd(*[gamma_trace(x) for x in t.args])
  161. return res
  162. t = _simplify_single_line(t)
  163. res = _trace_single_line(t)
  164. return res
  165. def _simplify_single_line(expression):
  166. """
  167. Simplify single-line product of gamma matrices.
  168. Examples
  169. ========
  170. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
  171. LorentzIndex, _simplify_single_line
  172. >>> from sympy.tensor.tensor import tensor_indices, TensorHead
  173. >>> p = TensorHead('p', [LorentzIndex])
  174. >>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
  175. >>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
  176. 0
  177. """
  178. t1, t2 = extract_type_tens(expression, GammaMatrix)
  179. if t1 != 1:
  180. t1 = kahane_simplify(t1)
  181. res = t1*t2
  182. return res
  183. def _trace_single_line(t):
  184. """
  185. Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
  186. Notes
  187. =====
  188. If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
  189. indices trace over them; otherwise traces are not implied (explain)
  190. Examples
  191. ========
  192. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
  193. LorentzIndex, _trace_single_line
  194. >>> from sympy.tensor.tensor import tensor_indices, TensorHead
  195. >>> p = TensorHead('p', [LorentzIndex])
  196. >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
  197. >>> _trace_single_line(G(i0)*G(i1))
  198. 4*metric(i0, i1)
  199. >>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
  200. 0
  201. """
  202. def _trace_single_line1(t):
  203. t = t.sorted_components()
  204. components = t.components
  205. ncomps = len(components)
  206. g = LorentzIndex.metric
  207. # gamma matirices are in a[i:j]
  208. hit = 0
  209. for i in range(ncomps):
  210. if components[i] == GammaMatrix:
  211. hit = 1
  212. break
  213. for j in range(i + hit, ncomps):
  214. if components[j] != GammaMatrix:
  215. break
  216. else:
  217. j = ncomps
  218. numG = j - i
  219. if numG == 0:
  220. tcoeff = t.coeff
  221. return t.nocoeff if tcoeff else t
  222. if numG % 2 == 1:
  223. return TensMul.from_data(S.Zero, [], [], [])
  224. elif numG > 4:
  225. # find the open matrix indices and connect them:
  226. a = t.split()
  227. ind1 = a[i].get_indices()[0]
  228. ind2 = a[i + 1].get_indices()[0]
  229. aa = a[:i] + a[i + 2:]
  230. t1 = tensor_mul(*aa)*g(ind1, ind2)
  231. t1 = t1.contract_metric(g)
  232. args = [t1]
  233. sign = 1
  234. for k in range(i + 2, j):
  235. sign = -sign
  236. ind2 = a[k].get_indices()[0]
  237. aa = a[:i] + a[i + 1:k] + a[k + 1:]
  238. t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
  239. t2 = t2.contract_metric(g)
  240. t2 = simplify_gpgp(t2, False)
  241. args.append(t2)
  242. t3 = TensAdd(*args)
  243. t3 = _trace_single_line(t3)
  244. return t3
  245. else:
  246. a = t.split()
  247. t1 = _gamma_trace1(*a[i:j])
  248. a2 = a[:i] + a[j:]
  249. t2 = tensor_mul(*a2)
  250. t3 = t1*t2
  251. if not t3:
  252. return t3
  253. t3 = t3.contract_metric(g)
  254. return t3
  255. t = t.expand()
  256. if isinstance(t, TensAdd):
  257. a = [_trace_single_line1(x)*x.coeff for x in t.args]
  258. return TensAdd(*a)
  259. elif isinstance(t, (Tensor, TensMul)):
  260. r = t.coeff*_trace_single_line1(t)
  261. return r
  262. else:
  263. return trace(t)
  264. def _gamma_trace1(*a):
  265. gctr = 4 # FIXME specific for d=4
  266. g = LorentzIndex.metric
  267. if not a:
  268. return gctr
  269. n = len(a)
  270. if n%2 == 1:
  271. #return TensMul.from_data(S.Zero, [], [], [])
  272. return S.Zero
  273. if n == 2:
  274. ind0 = a[0].get_indices()[0]
  275. ind1 = a[1].get_indices()[0]
  276. return gctr*g(ind0, ind1)
  277. if n == 4:
  278. ind0 = a[0].get_indices()[0]
  279. ind1 = a[1].get_indices()[0]
  280. ind2 = a[2].get_indices()[0]
  281. ind3 = a[3].get_indices()[0]
  282. return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
  283. g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
  284. def kahane_simplify(expression):
  285. r"""
  286. This function cancels contracted elements in a product of four
  287. dimensional gamma matrices, resulting in an expression equal to the given
  288. one, without the contracted gamma matrices.
  289. Parameters
  290. ==========
  291. `expression` the tensor expression containing the gamma matrices to simplify.
  292. Notes
  293. =====
  294. If spinor indices are given, the matrices must be given in
  295. the order given in the product.
  296. Algorithm
  297. =========
  298. The idea behind the algorithm is to use some well-known identities,
  299. i.e., for contractions enclosing an even number of `\gamma` matrices
  300. `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
  301. for an odd number of `\gamma` matrices
  302. `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
  303. Instead of repeatedly applying these identities to cancel out all contracted indices,
  304. it is possible to recognize the links that would result from such an operation,
  305. the problem is thus reduced to a simple rearrangement of free gamma matrices.
  306. Examples
  307. ========
  308. When using, always remember that the original expression coefficient
  309. has to be handled separately
  310. >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
  311. >>> from sympy.physics.hep.gamma_matrices import kahane_simplify
  312. >>> from sympy.tensor.tensor import tensor_indices
  313. >>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
  314. >>> ta = G(i0)*G(-i0)
  315. >>> kahane_simplify(ta)
  316. Matrix([
  317. [4, 0, 0, 0],
  318. [0, 4, 0, 0],
  319. [0, 0, 4, 0],
  320. [0, 0, 0, 4]])
  321. >>> tb = G(i0)*G(i1)*G(-i0)
  322. >>> kahane_simplify(tb)
  323. -2*GammaMatrix(i1)
  324. >>> t = G(i0)*G(-i0)
  325. >>> kahane_simplify(t)
  326. Matrix([
  327. [4, 0, 0, 0],
  328. [0, 4, 0, 0],
  329. [0, 0, 4, 0],
  330. [0, 0, 0, 4]])
  331. >>> t = G(i0)*G(-i0)
  332. >>> kahane_simplify(t)
  333. Matrix([
  334. [4, 0, 0, 0],
  335. [0, 4, 0, 0],
  336. [0, 0, 4, 0],
  337. [0, 0, 0, 4]])
  338. If there are no contractions, the same expression is returned
  339. >>> tc = G(i0)*G(i1)
  340. >>> kahane_simplify(tc)
  341. GammaMatrix(i0)*GammaMatrix(i1)
  342. References
  343. ==========
  344. [1] Algorithm for Reducing Contracted Products of gamma Matrices,
  345. Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
  346. """
  347. if isinstance(expression, Mul):
  348. return expression
  349. if isinstance(expression, TensAdd):
  350. return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
  351. if isinstance(expression, Tensor):
  352. return expression
  353. assert isinstance(expression, TensMul)
  354. gammas = expression.args
  355. for gamma in gammas:
  356. assert gamma.component == GammaMatrix
  357. free = expression.free
  358. # spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
  359. # if len(spinor_free) == 2:
  360. # spinor_free.sort(key=lambda x: x[2])
  361. # assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
  362. # assert spinor_free[0][2] == 0
  363. # elif spinor_free:
  364. # raise ValueError('spinor indices do not match')
  365. dum = []
  366. for dum_pair in expression.dum:
  367. if expression.index_types[dum_pair[0]] == LorentzIndex:
  368. dum.append((dum_pair[0], dum_pair[1]))
  369. dum = sorted(dum)
  370. if len(dum) == 0: # or GammaMatrixHead:
  371. # no contractions in `expression`, just return it.
  372. return expression
  373. # find the `first_dum_pos`, i.e. the position of the first contracted
  374. # gamma matrix, Kahane's algorithm as described in his paper requires the
  375. # gamma matrix expression to start with a contracted gamma matrix, this is
  376. # a workaround which ignores possible initial free indices, and re-adds
  377. # them later.
  378. first_dum_pos = min(map(min, dum))
  379. # for p1, p2, a1, a2 in expression.dum_in_args:
  380. # if p1 != 0 or p2 != 0:
  381. # # only Lorentz indices, skip Dirac indices:
  382. # continue
  383. # first_dum_pos = min(p1, p2)
  384. # break
  385. total_number = len(free) + len(dum)*2
  386. number_of_contractions = len(dum)
  387. free_pos = [None]*total_number
  388. for i in free:
  389. free_pos[i[1]] = i[0]
  390. # `index_is_free` is a list of booleans, to identify index position
  391. # and whether that index is free or dummy.
  392. index_is_free = [False]*total_number
  393. for i, indx in enumerate(free):
  394. index_is_free[indx[1]] = True
  395. # `links` is a dictionary containing the graph described in Kahane's paper,
  396. # to every key correspond one or two values, representing the linked indices.
  397. # All values in `links` are integers, negative numbers are used in the case
  398. # where it is necessary to insert gamma matrices between free indices, in
  399. # order to make Kahane's algorithm work (see paper).
  400. links = {i: [] for i in range(first_dum_pos, total_number)}
  401. # `cum_sign` is a step variable to mark the sign of every index, see paper.
  402. cum_sign = -1
  403. # `cum_sign_list` keeps storage for all `cum_sign` (every index).
  404. cum_sign_list = [None]*total_number
  405. block_free_count = 0
  406. # multiply `resulting_coeff` by the coefficient parameter, the rest
  407. # of the algorithm ignores a scalar coefficient.
  408. resulting_coeff = S.One
  409. # initialize a list of lists of indices. The outer list will contain all
  410. # additive tensor expressions, while the inner list will contain the
  411. # free indices (rearranged according to the algorithm).
  412. resulting_indices = [[]]
  413. # start to count the `connected_components`, which together with the number
  414. # of contractions, determines a -1 or +1 factor to be multiplied.
  415. connected_components = 1
  416. # First loop: here we fill `cum_sign_list`, and draw the links
  417. # among consecutive indices (they are stored in `links`). Links among
  418. # non-consecutive indices will be drawn later.
  419. for i, is_free in enumerate(index_is_free):
  420. # if `expression` starts with free indices, they are ignored here;
  421. # they are later added as they are to the beginning of all
  422. # `resulting_indices` list of lists of indices.
  423. if i < first_dum_pos:
  424. continue
  425. if is_free:
  426. block_free_count += 1
  427. # if previous index was free as well, draw an arch in `links`.
  428. if block_free_count > 1:
  429. links[i - 1].append(i)
  430. links[i].append(i - 1)
  431. else:
  432. # Change the sign of the index (`cum_sign`) if the number of free
  433. # indices preceding it is even.
  434. cum_sign *= 1 if (block_free_count % 2) else -1
  435. if block_free_count == 0 and i != first_dum_pos:
  436. # check if there are two consecutive dummy indices:
  437. # in this case create virtual indices with negative position,
  438. # these "virtual" indices represent the insertion of two
  439. # gamma^0 matrices to separate consecutive dummy indices, as
  440. # Kahane's algorithm requires dummy indices to be separated by
  441. # free indices. The product of two gamma^0 matrices is unity,
  442. # so the new expression being examined is the same as the
  443. # original one.
  444. if cum_sign == -1:
  445. links[-1-i] = [-1-i+1]
  446. links[-1-i+1] = [-1-i]
  447. if (i - cum_sign) in links:
  448. if i != first_dum_pos:
  449. links[i].append(i - cum_sign)
  450. if block_free_count != 0:
  451. if i - cum_sign < len(index_is_free):
  452. if index_is_free[i - cum_sign]:
  453. links[i - cum_sign].append(i)
  454. block_free_count = 0
  455. cum_sign_list[i] = cum_sign
  456. # The previous loop has only created links between consecutive free indices,
  457. # it is necessary to properly create links among dummy (contracted) indices,
  458. # according to the rules described in Kahane's paper. There is only one exception
  459. # to Kahane's rules: the negative indices, which handle the case of some
  460. # consecutive free indices (Kahane's paper just describes dummy indices
  461. # separated by free indices, hinting that free indices can be added without
  462. # altering the expression result).
  463. for i in dum:
  464. # get the positions of the two contracted indices:
  465. pos1 = i[0]
  466. pos2 = i[1]
  467. # create Kahane's upper links, i.e. the upper arcs between dummy
  468. # (i.e. contracted) indices:
  469. links[pos1].append(pos2)
  470. links[pos2].append(pos1)
  471. # create Kahane's lower links, this corresponds to the arcs below
  472. # the line described in the paper:
  473. # first we move `pos1` and `pos2` according to the sign of the indices:
  474. linkpos1 = pos1 + cum_sign_list[pos1]
  475. linkpos2 = pos2 + cum_sign_list[pos2]
  476. # otherwise, perform some checks before creating the lower arcs:
  477. # make sure we are not exceeding the total number of indices:
  478. if linkpos1 >= total_number:
  479. continue
  480. if linkpos2 >= total_number:
  481. continue
  482. # make sure we are not below the first dummy index in `expression`:
  483. if linkpos1 < first_dum_pos:
  484. continue
  485. if linkpos2 < first_dum_pos:
  486. continue
  487. # check if the previous loop created "virtual" indices between dummy
  488. # indices, in such a case relink `linkpos1` and `linkpos2`:
  489. if (-1-linkpos1) in links:
  490. linkpos1 = -1-linkpos1
  491. if (-1-linkpos2) in links:
  492. linkpos2 = -1-linkpos2
  493. # move only if not next to free index:
  494. if linkpos1 >= 0 and not index_is_free[linkpos1]:
  495. linkpos1 = pos1
  496. if linkpos2 >=0 and not index_is_free[linkpos2]:
  497. linkpos2 = pos2
  498. # create the lower arcs:
  499. if linkpos2 not in links[linkpos1]:
  500. links[linkpos1].append(linkpos2)
  501. if linkpos1 not in links[linkpos2]:
  502. links[linkpos2].append(linkpos1)
  503. # This loop starts from the `first_dum_pos` index (first dummy index)
  504. # walks through the graph deleting the visited indices from `links`,
  505. # it adds a gamma matrix for every free index in encounters, while it
  506. # completely ignores dummy indices and virtual indices.
  507. pointer = first_dum_pos
  508. previous_pointer = 0
  509. while True:
  510. if pointer in links:
  511. next_ones = links.pop(pointer)
  512. else:
  513. break
  514. if previous_pointer in next_ones:
  515. next_ones.remove(previous_pointer)
  516. previous_pointer = pointer
  517. if next_ones:
  518. pointer = next_ones[0]
  519. else:
  520. break
  521. if pointer == previous_pointer:
  522. break
  523. if pointer >=0 and free_pos[pointer] is not None:
  524. for ri in resulting_indices:
  525. ri.append(free_pos[pointer])
  526. # The following loop removes the remaining connected components in `links`.
  527. # If there are free indices inside a connected component, it gives a
  528. # contribution to the resulting expression given by the factor
  529. # `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
  530. # paper represented as {gamma_a, gamma_b, ... , gamma_z},
  531. # virtual indices are ignored. The variable `connected_components` is
  532. # increased by one for every connected component this loop encounters.
  533. # If the connected component has virtual and dummy indices only
  534. # (no free indices), it contributes to `resulting_indices` by a factor of two.
  535. # The multiplication by two is a result of the
  536. # factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
  537. # Note: curly brackets are meant as in the paper, as a generalized
  538. # multi-element anticommutator!
  539. while links:
  540. connected_components += 1
  541. pointer = min(links.keys())
  542. previous_pointer = pointer
  543. # the inner loop erases the visited indices from `links`, and it adds
  544. # all free indices to `prepend_indices` list, virtual indices are
  545. # ignored.
  546. prepend_indices = []
  547. while True:
  548. if pointer in links:
  549. next_ones = links.pop(pointer)
  550. else:
  551. break
  552. if previous_pointer in next_ones:
  553. if len(next_ones) > 1:
  554. next_ones.remove(previous_pointer)
  555. previous_pointer = pointer
  556. if next_ones:
  557. pointer = next_ones[0]
  558. if pointer >= first_dum_pos and free_pos[pointer] is not None:
  559. prepend_indices.insert(0, free_pos[pointer])
  560. # if `prepend_indices` is void, it means there are no free indices
  561. # in the loop (and it can be shown that there must be a virtual index),
  562. # loops of virtual indices only contribute by a factor of two:
  563. if len(prepend_indices) == 0:
  564. resulting_coeff *= 2
  565. # otherwise, add the free indices in `prepend_indices` to
  566. # the `resulting_indices`:
  567. else:
  568. expr1 = prepend_indices
  569. expr2 = list(reversed(prepend_indices))
  570. resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
  571. # sign correction, as described in Kahane's paper:
  572. resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
  573. # power of two factor, as described in Kahane's paper:
  574. resulting_coeff *= 2**(number_of_contractions)
  575. # If `first_dum_pos` is not zero, it means that there are trailing free gamma
  576. # matrices in front of `expression`, so multiply by them:
  577. resulting_indices = [ free_pos[0:first_dum_pos] + ri for ri in resulting_indices ]
  578. resulting_expr = S.Zero
  579. for i in resulting_indices:
  580. temp_expr = S.One
  581. for j in i:
  582. temp_expr *= GammaMatrix(j)
  583. resulting_expr += temp_expr
  584. t = resulting_coeff * resulting_expr
  585. t1 = None
  586. if isinstance(t, TensAdd):
  587. t1 = t.args[0]
  588. elif isinstance(t, TensMul):
  589. t1 = t
  590. if t1:
  591. pass
  592. else:
  593. t = eye(4)*t
  594. return t