图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4349 lines
145 KiB

  1. """
  2. This module defines tensors with abstract index notation.
  3. The abstract index notation has been first formalized by Penrose.
  4. Tensor indices are formal objects, with a tensor type; there is no
  5. notion of index range, it is only possible to assign the dimension,
  6. used to trace the Kronecker delta; the dimension can be a Symbol.
  7. The Einstein summation convention is used.
  8. The covariant indices are indicated with a minus sign in front of the index.
  9. For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c``
  10. contracted.
  11. A tensor expression ``t`` can be called; called with its
  12. indices in sorted order it is equal to itself:
  13. in the above example ``t(a, b) == t``;
  14. one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``.
  15. The contracted indices are dummy indices, internally they have no name,
  16. the indices being represented by a graph-like structure.
  17. Tensors are put in canonical form using ``canon_bp``, which uses
  18. the Butler-Portugal algorithm for canonicalization using the monoterm
  19. symmetries of the tensors.
  20. If there is a (anti)symmetric metric, the indices can be raised and
  21. lowered when the tensor is put in canonical form.
  22. """
  23. from typing import Any, Dict as tDict, List, Set as tSet, Tuple as tTuple
  24. from functools import reduce
  25. from abc import abstractmethod, ABCMeta
  26. from collections import defaultdict
  27. import operator
  28. import itertools
  29. from sympy.core.mul import prod
  30. from sympy.core.numbers import (Integer, Rational)
  31. from sympy.combinatorics import Permutation
  32. from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \
  33. bsgs_direct_product, canonicalize, riemann_bsgs
  34. from sympy.core import Basic, Expr, sympify, Add, Mul, S
  35. from sympy.core.assumptions import ManagedProperties
  36. from sympy.core.containers import Tuple, Dict
  37. from sympy.core.sorting import default_sort_key
  38. from sympy.core.symbol import Symbol, symbols
  39. from sympy.core.sympify import CantSympify, _sympify
  40. from sympy.core.operations import AssocOp
  41. from sympy.external.gmpy import SYMPY_INTS
  42. from sympy.matrices import eye
  43. from sympy.utilities.exceptions import (sympy_deprecation_warning,
  44. SymPyDeprecationWarning,
  45. ignore_warnings)
  46. from sympy.utilities.decorator import memoize_property, deprecated
  47. def deprecate_data():
  48. sympy_deprecation_warning(
  49. """
  50. The data attribute of TensorIndexType is deprecated. Use The
  51. replace_with_arrays() method instead.
  52. """,
  53. deprecated_since_version="1.4",
  54. active_deprecations_target="deprecated-tensorindextype-attrs",
  55. stacklevel=4,
  56. )
  57. def deprecate_fun_eval():
  58. sympy_deprecation_warning(
  59. """
  60. The Tensor.fun_eval() method is deprecated. Use
  61. Tensor.substitute_indices() instead.
  62. """,
  63. deprecated_since_version="1.5",
  64. active_deprecations_target="deprecated-tensor-fun-eval",
  65. stacklevel=4,
  66. )
  67. def deprecate_call():
  68. sympy_deprecation_warning(
  69. """
  70. Calling a tensor like Tensor(*indices) is deprecated. Use
  71. Tensor.substitute_indices() instead.
  72. """,
  73. deprecated_since_version="1.5",
  74. active_deprecations_target="deprecated-tensor-fun-eval",
  75. stacklevel=4,
  76. )
  77. class _IndexStructure(CantSympify):
  78. """
  79. This class handles the indices (free and dummy ones). It contains the
  80. algorithms to manage the dummy indices replacements and contractions of
  81. free indices under multiplications of tensor expressions, as well as stuff
  82. related to canonicalization sorting, getting the permutation of the
  83. expression and so on. It also includes tools to get the ``TensorIndex``
  84. objects corresponding to the given index structure.
  85. """
  86. def __init__(self, free, dum, index_types, indices, canon_bp=False):
  87. self.free = free
  88. self.dum = dum
  89. self.index_types = index_types
  90. self.indices = indices
  91. self._ext_rank = len(self.free) + 2*len(self.dum)
  92. self.dum.sort(key=lambda x: x[0])
  93. @staticmethod
  94. def from_indices(*indices):
  95. """
  96. Create a new ``_IndexStructure`` object from a list of ``indices``.
  97. Explanation
  98. ===========
  99. ``indices`` ``TensorIndex`` objects, the indices. Contractions are
  100. detected upon construction.
  101. Examples
  102. ========
  103. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure
  104. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  105. >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
  106. >>> _IndexStructure.from_indices(m0, m1, -m1, m3)
  107. _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz])
  108. """
  109. free, dum = _IndexStructure._free_dum_from_indices(*indices)
  110. index_types = [i.tensor_index_type for i in indices]
  111. indices = _IndexStructure._replace_dummy_names(indices, free, dum)
  112. return _IndexStructure(free, dum, index_types, indices)
  113. @staticmethod
  114. def from_components_free_dum(components, free, dum):
  115. index_types = []
  116. for component in components:
  117. index_types.extend(component.index_types)
  118. indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types)
  119. return _IndexStructure(free, dum, index_types, indices)
  120. @staticmethod
  121. def _free_dum_from_indices(*indices):
  122. """
  123. Convert ``indices`` into ``free``, ``dum`` for single component tensor.
  124. Explanation
  125. ===========
  126. ``free`` list of tuples ``(index, pos, 0)``,
  127. where ``pos`` is the position of index in
  128. the list of indices formed by the component tensors
  129. ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)``
  130. Examples
  131. ========
  132. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \
  133. _IndexStructure
  134. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  135. >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz)
  136. >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3)
  137. ([(m0, 0), (m3, 3)], [(1, 2)])
  138. """
  139. n = len(indices)
  140. if n == 1:
  141. return [(indices[0], 0)], []
  142. # find the positions of the free indices and of the dummy indices
  143. free = [True]*len(indices)
  144. index_dict = {}
  145. dum = []
  146. for i, index in enumerate(indices):
  147. name = index.name
  148. typ = index.tensor_index_type
  149. contr = index.is_up
  150. if (name, typ) in index_dict:
  151. # found a pair of dummy indices
  152. is_contr, pos = index_dict[(name, typ)]
  153. # check consistency and update free
  154. if is_contr:
  155. if contr:
  156. raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i))
  157. else:
  158. free[pos] = False
  159. free[i] = False
  160. else:
  161. if contr:
  162. free[pos] = False
  163. free[i] = False
  164. else:
  165. raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i))
  166. if contr:
  167. dum.append((i, pos))
  168. else:
  169. dum.append((pos, i))
  170. else:
  171. index_dict[(name, typ)] = index.is_up, i
  172. free = [(index, i) for i, index in enumerate(indices) if free[i]]
  173. free.sort()
  174. return free, dum
  175. def get_indices(self):
  176. """
  177. Get a list of indices, creating new tensor indices to complete dummy indices.
  178. """
  179. return self.indices[:]
  180. @staticmethod
  181. def generate_indices_from_free_dum_index_types(free, dum, index_types):
  182. indices = [None]*(len(free)+2*len(dum))
  183. for idx, pos in free:
  184. indices[pos] = idx
  185. generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
  186. for pos1, pos2 in dum:
  187. typ1 = index_types[pos1]
  188. indname = generate_dummy_name(typ1)
  189. indices[pos1] = TensorIndex(indname, typ1, True)
  190. indices[pos2] = TensorIndex(indname, typ1, False)
  191. return _IndexStructure._replace_dummy_names(indices, free, dum)
  192. @staticmethod
  193. def _get_generator_for_dummy_indices(free):
  194. cdt = defaultdict(int)
  195. # if the free indices have names with dummy_name, start with an
  196. # index higher than those for the dummy indices
  197. # to avoid name collisions
  198. for indx, ipos in free:
  199. if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name:
  200. cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1)
  201. def dummy_name_gen(tensor_index_type):
  202. nd = str(cdt[tensor_index_type])
  203. cdt[tensor_index_type] += 1
  204. return tensor_index_type.dummy_name + '_' + nd
  205. return dummy_name_gen
  206. @staticmethod
  207. def _replace_dummy_names(indices, free, dum):
  208. dum.sort(key=lambda x: x[0])
  209. new_indices = [ind for ind in indices]
  210. assert len(indices) == len(free) + 2*len(dum)
  211. generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free)
  212. for ipos1, ipos2 in dum:
  213. typ1 = new_indices[ipos1].tensor_index_type
  214. indname = generate_dummy_name(typ1)
  215. new_indices[ipos1] = TensorIndex(indname, typ1, True)
  216. new_indices[ipos2] = TensorIndex(indname, typ1, False)
  217. return new_indices
  218. def get_free_indices(self): # type: () -> List[TensorIndex]
  219. """
  220. Get a list of free indices.
  221. """
  222. # get sorted indices according to their position:
  223. free = sorted(self.free, key=lambda x: x[1])
  224. return [i[0] for i in free]
  225. def __str__(self):
  226. return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types)
  227. def __repr__(self):
  228. return self.__str__()
  229. def _get_sorted_free_indices_for_canon(self):
  230. sorted_free = self.free[:]
  231. sorted_free.sort(key=lambda x: x[0])
  232. return sorted_free
  233. def _get_sorted_dum_indices_for_canon(self):
  234. return sorted(self.dum, key=lambda x: x[0])
  235. def _get_lexicographically_sorted_index_types(self):
  236. permutation = self.indices_canon_args()[0]
  237. index_types = [None]*self._ext_rank
  238. for i, it in enumerate(self.index_types):
  239. index_types[permutation(i)] = it
  240. return index_types
  241. def _get_lexicographically_sorted_indices(self):
  242. permutation = self.indices_canon_args()[0]
  243. indices = [None]*self._ext_rank
  244. for i, it in enumerate(self.indices):
  245. indices[permutation(i)] = it
  246. return indices
  247. def perm2tensor(self, g, is_canon_bp=False):
  248. """
  249. Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``.
  250. Explanation
  251. ===========
  252. ``g`` permutation corresponding to the tensor in the representation
  253. used in canonicalization
  254. ``is_canon_bp`` if True, then ``g`` is the permutation
  255. corresponding to the canonical form of the tensor
  256. """
  257. sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()]
  258. lex_index_types = self._get_lexicographically_sorted_index_types()
  259. lex_indices = self._get_lexicographically_sorted_indices()
  260. nfree = len(sorted_free)
  261. rank = self._ext_rank
  262. dum = [[None]*2 for i in range((rank - nfree)//2)]
  263. free = []
  264. index_types = [None]*rank
  265. indices = [None]*rank
  266. for i in range(rank):
  267. gi = g[i]
  268. index_types[i] = lex_index_types[gi]
  269. indices[i] = lex_indices[gi]
  270. if gi < nfree:
  271. ind = sorted_free[gi]
  272. assert index_types[i] == sorted_free[gi].tensor_index_type
  273. free.append((ind, i))
  274. else:
  275. j = gi - nfree
  276. idum, cov = divmod(j, 2)
  277. if cov:
  278. dum[idum][1] = i
  279. else:
  280. dum[idum][0] = i
  281. dum = [tuple(x) for x in dum]
  282. return _IndexStructure(free, dum, index_types, indices)
  283. def indices_canon_args(self):
  284. """
  285. Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize``
  286. See ``canonicalize`` in ``tensor_can.py`` in combinatorics module.
  287. """
  288. # to be called after sorted_components
  289. from sympy.combinatorics.permutations import _af_new
  290. n = self._ext_rank
  291. g = [None]*n + [n, n+1]
  292. # Converts the symmetry of the metric into msym from .canonicalize()
  293. # method in the combinatorics module
  294. def metric_symmetry_to_msym(metric):
  295. if metric is None:
  296. return None
  297. sym = metric.symmetry
  298. if sym == TensorSymmetry.fully_symmetric(2):
  299. return 0
  300. if sym == TensorSymmetry.fully_symmetric(-2):
  301. return 1
  302. return None
  303. # ordered indices: first the free indices, ordered by types
  304. # then the dummy indices, ordered by types and contravariant before
  305. # covariant
  306. # g[position in tensor] = position in ordered indices
  307. for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()):
  308. g[ipos] = i
  309. pos = len(self.free)
  310. j = len(self.free)
  311. dummies = []
  312. prev = None
  313. a = []
  314. msym = []
  315. for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon():
  316. g[ipos1] = j
  317. g[ipos2] = j + 1
  318. j += 2
  319. typ = self.index_types[ipos1]
  320. if typ != prev:
  321. if a:
  322. dummies.append(a)
  323. a = [pos, pos + 1]
  324. prev = typ
  325. msym.append(metric_symmetry_to_msym(typ.metric))
  326. else:
  327. a.extend([pos, pos + 1])
  328. pos += 2
  329. if a:
  330. dummies.append(a)
  331. return _af_new(g), dummies, msym
  332. def components_canon_args(components):
  333. numtyp = []
  334. prev = None
  335. for t in components:
  336. if t == prev:
  337. numtyp[-1][1] += 1
  338. else:
  339. prev = t
  340. numtyp.append([prev, 1])
  341. v = []
  342. for h, n in numtyp:
  343. if h.comm in (0, 1):
  344. comm = h.comm
  345. else:
  346. comm = TensorManager.get_comm(h.comm, h.comm)
  347. v.append((h.symmetry.base, h.symmetry.generators, n, comm))
  348. return v
  349. class _TensorDataLazyEvaluator(CantSympify):
  350. """
  351. EXPERIMENTAL: do not rely on this class, it may change without deprecation
  352. warnings in future versions of SymPy.
  353. Explanation
  354. ===========
  355. This object contains the logic to associate components data to a tensor
  356. expression. Components data are set via the ``.data`` property of tensor
  357. expressions, is stored inside this class as a mapping between the tensor
  358. expression and the ``ndarray``.
  359. Computations are executed lazily: whereas the tensor expressions can have
  360. contractions, tensor products, and additions, components data are not
  361. computed until they are accessed by reading the ``.data`` property
  362. associated to the tensor expression.
  363. """
  364. _substitutions_dict = dict() # type: tDict[Any, Any]
  365. _substitutions_dict_tensmul = dict() # type: tDict[Any, Any]
  366. def __getitem__(self, key):
  367. dat = self._get(key)
  368. if dat is None:
  369. return None
  370. from .array import NDimArray
  371. if not isinstance(dat, NDimArray):
  372. return dat
  373. if dat.rank() == 0:
  374. return dat[()]
  375. elif dat.rank() == 1 and len(dat) == 1:
  376. return dat[0]
  377. return dat
  378. def _get(self, key):
  379. """
  380. Retrieve ``data`` associated with ``key``.
  381. Explanation
  382. ===========
  383. This algorithm looks into ``self._substitutions_dict`` for all
  384. ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a
  385. TensorHead instance). It reconstructs the components data that the
  386. tensor expression should have by performing on components data the
  387. operations that correspond to the abstract tensor operations applied.
  388. Metric tensor is handled in a different manner: it is pre-computed in
  389. ``self._substitutions_dict_tensmul``.
  390. """
  391. if key in self._substitutions_dict:
  392. return self._substitutions_dict[key]
  393. if isinstance(key, TensorHead):
  394. return None
  395. if isinstance(key, Tensor):
  396. # special case to handle metrics. Metric tensors cannot be
  397. # constructed through contraction by the metric, their
  398. # components show if they are a matrix or its inverse.
  399. signature = tuple([i.is_up for i in key.get_indices()])
  400. srch = (key.component,) + signature
  401. if srch in self._substitutions_dict_tensmul:
  402. return self._substitutions_dict_tensmul[srch]
  403. array_list = [self.data_from_tensor(key)]
  404. return self.data_contract_dum(array_list, key.dum, key.ext_rank)
  405. if isinstance(key, TensMul):
  406. tensmul_args = key.args
  407. if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1:
  408. # special case to handle metrics. Metric tensors cannot be
  409. # constructed through contraction by the metric, their
  410. # components show if they are a matrix or its inverse.
  411. signature = tuple([i.is_up for i in tensmul_args[0].get_indices()])
  412. srch = (tensmul_args[0].components[0],) + signature
  413. if srch in self._substitutions_dict_tensmul:
  414. return self._substitutions_dict_tensmul[srch]
  415. #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)]
  416. data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)]
  417. coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)])
  418. if all(i is None for i in data_list):
  419. return None
  420. if any(i is None for i in data_list):
  421. raise ValueError("Mixing tensors with associated components "\
  422. "data with tensors without components data")
  423. data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank)
  424. return coeff*data_result
  425. if isinstance(key, TensAdd):
  426. data_list = []
  427. free_args_list = []
  428. for arg in key.args:
  429. if isinstance(arg, TensExpr):
  430. data_list.append(arg.data)
  431. free_args_list.append([x[0] for x in arg.free])
  432. else:
  433. data_list.append(arg)
  434. free_args_list.append([])
  435. if all(i is None for i in data_list):
  436. return None
  437. if any(i is None for i in data_list):
  438. raise ValueError("Mixing tensors with associated components "\
  439. "data with tensors without components data")
  440. sum_list = []
  441. from .array import permutedims
  442. for data, free_args in zip(data_list, free_args_list):
  443. if len(free_args) < 2:
  444. sum_list.append(data)
  445. else:
  446. free_args_pos = {y: x for x, y in enumerate(free_args)}
  447. axes = [free_args_pos[arg] for arg in key.free_args]
  448. sum_list.append(permutedims(data, axes))
  449. return reduce(lambda x, y: x+y, sum_list)
  450. return None
  451. @staticmethod
  452. def data_contract_dum(ndarray_list, dum, ext_rank):
  453. from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray
  454. arrays = list(map(MutableDenseNDimArray, ndarray_list))
  455. prodarr = tensorproduct(*arrays)
  456. return tensorcontraction(prodarr, *dum)
  457. def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead):
  458. """
  459. This method is used when assigning components data to a ``TensMul``
  460. object, it converts components data to a fully contravariant ndarray,
  461. which is then stored according to the ``TensorHead`` key.
  462. """
  463. if data is None:
  464. return None
  465. return self._correct_signature_from_indices(
  466. data,
  467. tensmul.get_indices(),
  468. tensmul.free,
  469. tensmul.dum,
  470. True)
  471. def data_from_tensor(self, tensor):
  472. """
  473. This method corrects the components data to the right signature
  474. (covariant/contravariant) using the metric associated with each
  475. ``TensorIndexType``.
  476. """
  477. tensorhead = tensor.component
  478. if tensorhead.data is None:
  479. return None
  480. return self._correct_signature_from_indices(
  481. tensorhead.data,
  482. tensor.get_indices(),
  483. tensor.free,
  484. tensor.dum)
  485. def _assign_data_to_tensor_expr(self, key, data):
  486. if isinstance(key, TensAdd):
  487. raise ValueError('cannot assign data to TensAdd')
  488. # here it is assumed that `key` is a `TensMul` instance.
  489. if len(key.components) != 1:
  490. raise ValueError('cannot assign data to TensMul with multiple components')
  491. tensorhead = key.components[0]
  492. newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead)
  493. return tensorhead, newdata
  494. def _check_permutations_on_data(self, tens, data):
  495. from .array import permutedims
  496. from .array.arrayop import Flatten
  497. if isinstance(tens, TensorHead):
  498. rank = tens.rank
  499. generators = tens.symmetry.generators
  500. elif isinstance(tens, Tensor):
  501. rank = tens.rank
  502. generators = tens.components[0].symmetry.generators
  503. elif isinstance(tens, TensorIndexType):
  504. rank = tens.metric.rank
  505. generators = tens.metric.symmetry.generators
  506. # Every generator is a permutation, check that by permuting the array
  507. # by that permutation, the array will be the same, except for a
  508. # possible sign change if the permutation admits it.
  509. for gener in generators:
  510. sign_change = +1 if (gener(rank) == rank) else -1
  511. data_swapped = data
  512. last_data = data
  513. permute_axes = list(map(gener, list(range(rank))))
  514. # the order of a permutation is the number of times to get the
  515. # identity by applying that permutation.
  516. for i in range(gener.order()-1):
  517. data_swapped = permutedims(data_swapped, permute_axes)
  518. # if any value in the difference array is non-zero, raise an error:
  519. if any(Flatten(last_data - sign_change*data_swapped)):
  520. raise ValueError("Component data symmetry structure error")
  521. last_data = data_swapped
  522. def __setitem__(self, key, value):
  523. """
  524. Set the components data of a tensor object/expression.
  525. Explanation
  526. ===========
  527. Components data are transformed to the all-contravariant form and stored
  528. with the corresponding ``TensorHead`` object. If a ``TensorHead`` object
  529. cannot be uniquely identified, it will raise an error.
  530. """
  531. data = _TensorDataLazyEvaluator.parse_data(value)
  532. self._check_permutations_on_data(key, data)
  533. # TensorHead and TensorIndexType can be assigned data directly, while
  534. # TensMul must first convert data to a fully contravariant form, and
  535. # assign it to its corresponding TensorHead single component.
  536. if not isinstance(key, (TensorHead, TensorIndexType)):
  537. key, data = self._assign_data_to_tensor_expr(key, data)
  538. if isinstance(key, TensorHead):
  539. for dim, indextype in zip(data.shape, key.index_types):
  540. if indextype.data is None:
  541. raise ValueError("index type {} has no components data"\
  542. " associated (needed to raise/lower index)".format(indextype))
  543. if not indextype.dim.is_number:
  544. continue
  545. if dim != indextype.dim:
  546. raise ValueError("wrong dimension of ndarray")
  547. self._substitutions_dict[key] = data
  548. def __delitem__(self, key):
  549. del self._substitutions_dict[key]
  550. def __contains__(self, key):
  551. return key in self._substitutions_dict
  552. def add_metric_data(self, metric, data):
  553. """
  554. Assign data to the ``metric`` tensor. The metric tensor behaves in an
  555. anomalous way when raising and lowering indices.
  556. Explanation
  557. ===========
  558. A fully covariant metric is the inverse transpose of the fully
  559. contravariant metric (it is meant matrix inverse). If the metric is
  560. symmetric, the transpose is not necessary and mixed
  561. covariant/contravariant metrics are Kronecker deltas.
  562. """
  563. # hard assignment, data should not be added to `TensorHead` for metric:
  564. # the problem with `TensorHead` is that the metric is anomalous, i.e.
  565. # raising and lowering the index means considering the metric or its
  566. # inverse, this is not the case for other tensors.
  567. self._substitutions_dict_tensmul[metric, True, True] = data
  568. inverse_transpose = self.inverse_transpose_matrix(data)
  569. # in symmetric spaces, the transpose is the same as the original matrix,
  570. # the full covariant metric tensor is the inverse transpose, so this
  571. # code will be able to handle non-symmetric metrics.
  572. self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose
  573. # now mixed cases, these are identical to the unit matrix if the metric
  574. # is symmetric.
  575. m = data.tomatrix()
  576. invt = inverse_transpose.tomatrix()
  577. self._substitutions_dict_tensmul[metric, True, False] = m * invt
  578. self._substitutions_dict_tensmul[metric, False, True] = invt * m
  579. @staticmethod
  580. def _flip_index_by_metric(data, metric, pos):
  581. from .array import tensorproduct, tensorcontraction
  582. mdim = metric.rank()
  583. ddim = data.rank()
  584. if pos == 0:
  585. data = tensorcontraction(
  586. tensorproduct(
  587. metric,
  588. data
  589. ),
  590. (1, mdim+pos)
  591. )
  592. else:
  593. data = tensorcontraction(
  594. tensorproduct(
  595. data,
  596. metric
  597. ),
  598. (pos, ddim)
  599. )
  600. return data
  601. @staticmethod
  602. def inverse_matrix(ndarray):
  603. m = ndarray.tomatrix().inv()
  604. return _TensorDataLazyEvaluator.parse_data(m)
  605. @staticmethod
  606. def inverse_transpose_matrix(ndarray):
  607. m = ndarray.tomatrix().inv().T
  608. return _TensorDataLazyEvaluator.parse_data(m)
  609. @staticmethod
  610. def _correct_signature_from_indices(data, indices, free, dum, inverse=False):
  611. """
  612. Utility function to correct the values inside the components data
  613. ndarray according to whether indices are covariant or contravariant.
  614. It uses the metric matrix to lower values of covariant indices.
  615. """
  616. # change the ndarray values according covariantness/contravariantness of the indices
  617. # use the metric
  618. for i, indx in enumerate(indices):
  619. if not indx.is_up and not inverse:
  620. data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i)
  621. elif not indx.is_up and inverse:
  622. data = _TensorDataLazyEvaluator._flip_index_by_metric(
  623. data,
  624. _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data),
  625. i
  626. )
  627. return data
  628. @staticmethod
  629. def _sort_data_axes(old, new):
  630. from .array import permutedims
  631. new_data = old.data.copy()
  632. old_free = [i[0] for i in old.free]
  633. new_free = [i[0] for i in new.free]
  634. for i in range(len(new_free)):
  635. for j in range(i, len(old_free)):
  636. if old_free[j] == new_free[i]:
  637. old_free[i], old_free[j] = old_free[j], old_free[i]
  638. new_data = permutedims(new_data, (i, j))
  639. break
  640. return new_data
  641. @staticmethod
  642. def add_rearrange_tensmul_parts(new_tensmul, old_tensmul):
  643. def sorted_compo():
  644. return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul)
  645. _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo()
  646. @staticmethod
  647. def parse_data(data):
  648. """
  649. Transform ``data`` to array. The parameter ``data`` may
  650. contain data in various formats, e.g. nested lists, SymPy ``Matrix``,
  651. and so on.
  652. Examples
  653. ========
  654. >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator
  655. >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12])
  656. [1, 3, -6, 12]
  657. >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]])
  658. [[1, 2], [4, 7]]
  659. """
  660. from .array import MutableDenseNDimArray
  661. if not isinstance(data, MutableDenseNDimArray):
  662. if len(data) == 2 and hasattr(data[0], '__call__'):
  663. data = MutableDenseNDimArray(data[0], data[1])
  664. else:
  665. data = MutableDenseNDimArray(data)
  666. return data
  667. _tensor_data_substitution_dict = _TensorDataLazyEvaluator()
  668. class _TensorManager:
  669. """
  670. Class to manage tensor properties.
  671. Notes
  672. =====
  673. Tensors belong to tensor commutation groups; each group has a label
  674. ``comm``; there are predefined labels:
  675. ``0`` tensors commuting with any other tensor
  676. ``1`` tensors anticommuting among themselves
  677. ``2`` tensors not commuting, apart with those with ``comm=0``
  678. Other groups can be defined using ``set_comm``; tensors in those
  679. groups commute with those with ``comm=0``; by default they
  680. do not commute with any other group.
  681. """
  682. def __init__(self):
  683. self._comm_init()
  684. def _comm_init(self):
  685. self._comm = [{} for i in range(3)]
  686. for i in range(3):
  687. self._comm[0][i] = 0
  688. self._comm[i][0] = 0
  689. self._comm[1][1] = 1
  690. self._comm[2][1] = None
  691. self._comm[1][2] = None
  692. self._comm_symbols2i = {0:0, 1:1, 2:2}
  693. self._comm_i2symbol = {0:0, 1:1, 2:2}
  694. @property
  695. def comm(self):
  696. return self._comm
  697. def comm_symbols2i(self, i):
  698. """
  699. Get the commutation group number corresponding to ``i``.
  700. ``i`` can be a symbol or a number or a string.
  701. If ``i`` is not already defined its commutation group number
  702. is set.
  703. """
  704. if i not in self._comm_symbols2i:
  705. n = len(self._comm)
  706. self._comm.append({})
  707. self._comm[n][0] = 0
  708. self._comm[0][n] = 0
  709. self._comm_symbols2i[i] = n
  710. self._comm_i2symbol[n] = i
  711. return n
  712. return self._comm_symbols2i[i]
  713. def comm_i2symbol(self, i):
  714. """
  715. Returns the symbol corresponding to the commutation group number.
  716. """
  717. return self._comm_i2symbol[i]
  718. def set_comm(self, i, j, c):
  719. """
  720. Set the commutation parameter ``c`` for commutation groups ``i, j``.
  721. Parameters
  722. ==========
  723. i, j : symbols representing commutation groups
  724. c : group commutation number
  725. Notes
  726. =====
  727. ``i, j`` can be symbols, strings or numbers,
  728. apart from ``0, 1`` and ``2`` which are reserved respectively
  729. for commuting, anticommuting tensors and tensors not commuting
  730. with any other group apart with the commuting tensors.
  731. For the remaining cases, use this method to set the commutation rules;
  732. by default ``c=None``.
  733. The group commutation number ``c`` is assigned in correspondence
  734. to the group commutation symbols; it can be
  735. 0 commuting
  736. 1 anticommuting
  737. None no commutation property
  738. Examples
  739. ========
  740. ``G`` and ``GH`` do not commute with themselves and commute with
  741. each other; A is commuting.
  742. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry
  743. >>> Lorentz = TensorIndexType('Lorentz')
  744. >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz)
  745. >>> A = TensorHead('A', [Lorentz])
  746. >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
  747. >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm')
  748. >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0)
  749. >>> (GH(i1)*G(i0)).canon_bp()
  750. G(i0)*GH(i1)
  751. >>> (G(i1)*G(i0)).canon_bp()
  752. G(i1)*G(i0)
  753. >>> (G(i1)*A(i0)).canon_bp()
  754. A(i0)*G(i1)
  755. """
  756. if c not in (0, 1, None):
  757. raise ValueError('`c` can assume only the values 0, 1 or None')
  758. if i not in self._comm_symbols2i:
  759. n = len(self._comm)
  760. self._comm.append({})
  761. self._comm[n][0] = 0
  762. self._comm[0][n] = 0
  763. self._comm_symbols2i[i] = n
  764. self._comm_i2symbol[n] = i
  765. if j not in self._comm_symbols2i:
  766. n = len(self._comm)
  767. self._comm.append({})
  768. self._comm[0][n] = 0
  769. self._comm[n][0] = 0
  770. self._comm_symbols2i[j] = n
  771. self._comm_i2symbol[n] = j
  772. ni = self._comm_symbols2i[i]
  773. nj = self._comm_symbols2i[j]
  774. self._comm[ni][nj] = c
  775. self._comm[nj][ni] = c
  776. def set_comms(self, *args):
  777. """
  778. Set the commutation group numbers ``c`` for symbols ``i, j``.
  779. Parameters
  780. ==========
  781. args : sequence of ``(i, j, c)``
  782. """
  783. for i, j, c in args:
  784. self.set_comm(i, j, c)
  785. def get_comm(self, i, j):
  786. """
  787. Return the commutation parameter for commutation group numbers ``i, j``
  788. see ``_TensorManager.set_comm``
  789. """
  790. return self._comm[i].get(j, 0 if i == 0 or j == 0 else None)
  791. def clear(self):
  792. """
  793. Clear the TensorManager.
  794. """
  795. self._comm_init()
  796. TensorManager = _TensorManager()
  797. class TensorIndexType(Basic):
  798. """
  799. A TensorIndexType is characterized by its name and its metric.
  800. Parameters
  801. ==========
  802. name : name of the tensor type
  803. dummy_name : name of the head of dummy indices
  804. dim : dimension, it can be a symbol or an integer or ``None``
  805. eps_dim : dimension of the epsilon tensor
  806. metric_symmetry : integer that denotes metric symmetry or ``None`` for no metirc
  807. metric_name : string with the name of the metric tensor
  808. Attributes
  809. ==========
  810. ``metric`` : the metric tensor
  811. ``delta`` : ``Kronecker delta``
  812. ``epsilon`` : the ``Levi-Civita epsilon`` tensor
  813. ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis.
  814. Notes
  815. =====
  816. The possible values of the ``metric_symmetry`` parameter are:
  817. ``1`` : metric tensor is fully symmetric
  818. ``0`` : metric tensor possesses no index symmetry
  819. ``-1`` : metric tensor is fully antisymmetric
  820. ``None``: there is no metric tensor (metric equals to ``None``)
  821. The metric is assumed to be symmetric by default. It can also be set
  822. to a custom tensor by the ``.set_metric()`` method.
  823. If there is a metric the metric is used to raise and lower indices.
  824. In the case of non-symmetric metric, the following raising and
  825. lowering conventions will be adopted:
  826. ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)``
  827. From these it is easy to find:
  828. ``g(-a, b) = delta(-a, b)``
  829. where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta``
  830. (see ``TensorIndex`` for the conventions on indices).
  831. For antisymmetric metrics there is also the following equality:
  832. ``g(a, -b) = -delta(a, -b)``
  833. If there is no metric it is not possible to raise or lower indices;
  834. e.g. the index of the defining representation of ``SU(N)``
  835. is 'covariant' and the conjugate representation is
  836. 'contravariant'; for ``N > 2`` they are linearly independent.
  837. ``eps_dim`` is by default equal to ``dim``, if the latter is an integer;
  838. else it can be assigned (for use in naive dimensional regularization);
  839. if ``eps_dim`` is not an integer ``epsilon`` is ``None``.
  840. Examples
  841. ========
  842. >>> from sympy.tensor.tensor import TensorIndexType
  843. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  844. >>> Lorentz.metric
  845. metric(Lorentz,Lorentz)
  846. """
  847. def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None,
  848. metric_symmetry=1, metric_name='metric', **kwargs):
  849. if 'dummy_fmt' in kwargs:
  850. dummy_fmt = kwargs['dummy_fmt']
  851. sympy_deprecation_warning(
  852. f"""
  853. The dummy_fmt keyword to TensorIndexType is deprecated. Use
  854. dummy_name={dummy_fmt} instead.
  855. """,
  856. deprecated_since_version="1.5",
  857. active_deprecations_target="deprecated-tensorindextype-dummy-fmt",
  858. )
  859. dummy_name = dummy_fmt
  860. if isinstance(name, str):
  861. name = Symbol(name)
  862. if dummy_name is None:
  863. dummy_name = str(name)[0]
  864. if isinstance(dummy_name, str):
  865. dummy_name = Symbol(dummy_name)
  866. if dim is None:
  867. dim = Symbol("dim_" + dummy_name.name)
  868. else:
  869. dim = sympify(dim)
  870. if eps_dim is None:
  871. eps_dim = dim
  872. else:
  873. eps_dim = sympify(eps_dim)
  874. metric_symmetry = sympify(metric_symmetry)
  875. if isinstance(metric_name, str):
  876. metric_name = Symbol(metric_name)
  877. if 'metric' in kwargs:
  878. SymPyDeprecationWarning(
  879. """
  880. The 'metric' keyword argument to TensorIndexType is
  881. deprecated. Use the 'metric_symmetry' keyword argument or the
  882. TensorIndexType.set_metric() method instead.
  883. """,
  884. deprecated_since_version="1.5",
  885. active_deprecations_target="deprecated-tensorindextype-metric",
  886. )
  887. metric = kwargs.get('metric')
  888. if metric is not None:
  889. if metric in (True, False, 0, 1):
  890. metric_name = 'metric'
  891. #metric_antisym = metric
  892. else:
  893. metric_name = metric.name
  894. #metric_antisym = metric.antisym
  895. if metric:
  896. metric_symmetry = -1
  897. else:
  898. metric_symmetry = 1
  899. obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim,
  900. metric_symmetry, metric_name)
  901. obj._autogenerated = []
  902. return obj
  903. @property
  904. def name(self):
  905. return self.args[0].name
  906. @property
  907. def dummy_name(self):
  908. return self.args[1].name
  909. @property
  910. def dim(self):
  911. return self.args[2]
  912. @property
  913. def eps_dim(self):
  914. return self.args[3]
  915. @memoize_property
  916. def metric(self):
  917. metric_symmetry = self.args[4]
  918. metric_name = self.args[5]
  919. if metric_symmetry is None:
  920. return None
  921. if metric_symmetry == 0:
  922. symmetry = TensorSymmetry.no_symmetry(2)
  923. elif metric_symmetry == 1:
  924. symmetry = TensorSymmetry.fully_symmetric(2)
  925. elif metric_symmetry == -1:
  926. symmetry = TensorSymmetry.fully_symmetric(-2)
  927. return TensorHead(metric_name, [self]*2, symmetry)
  928. @memoize_property
  929. def delta(self):
  930. return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2))
  931. @memoize_property
  932. def epsilon(self):
  933. if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)):
  934. return None
  935. symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim)
  936. return TensorHead('Eps', [self]*self.eps_dim, symmetry)
  937. def set_metric(self, tensor):
  938. self._metric = tensor
  939. def __lt__(self, other):
  940. return self.name < other.name
  941. def __str__(self):
  942. return self.name
  943. __repr__ = __str__
  944. # Everything below this line is deprecated
  945. @property
  946. def data(self):
  947. deprecate_data()
  948. with ignore_warnings(SymPyDeprecationWarning):
  949. return _tensor_data_substitution_dict[self]
  950. @data.setter
  951. def data(self, data):
  952. deprecate_data()
  953. # This assignment is a bit controversial, should metric components be assigned
  954. # to the metric only or also to the TensorIndexType object? The advantage here
  955. # is the ability to assign a 1D array and transform it to a 2D diagonal array.
  956. from .array import MutableDenseNDimArray
  957. data = _TensorDataLazyEvaluator.parse_data(data)
  958. if data.rank() > 2:
  959. raise ValueError("data have to be of rank 1 (diagonal metric) or 2.")
  960. if data.rank() == 1:
  961. if self.dim.is_number:
  962. nda_dim = data.shape[0]
  963. if nda_dim != self.dim:
  964. raise ValueError("Dimension mismatch")
  965. dim = data.shape[0]
  966. newndarray = MutableDenseNDimArray.zeros(dim, dim)
  967. for i, val in enumerate(data):
  968. newndarray[i, i] = val
  969. data = newndarray
  970. dim1, dim2 = data.shape
  971. if dim1 != dim2:
  972. raise ValueError("Non-square matrix tensor.")
  973. if self.dim.is_number:
  974. if self.dim != dim1:
  975. raise ValueError("Dimension mismatch")
  976. _tensor_data_substitution_dict[self] = data
  977. _tensor_data_substitution_dict.add_metric_data(self.metric, data)
  978. with ignore_warnings(SymPyDeprecationWarning):
  979. delta = self.get_kronecker_delta()
  980. i1 = TensorIndex('i1', self)
  981. i2 = TensorIndex('i2', self)
  982. with ignore_warnings(SymPyDeprecationWarning):
  983. delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1))
  984. @data.deleter
  985. def data(self):
  986. deprecate_data()
  987. with ignore_warnings(SymPyDeprecationWarning):
  988. if self in _tensor_data_substitution_dict:
  989. del _tensor_data_substitution_dict[self]
  990. if self.metric in _tensor_data_substitution_dict:
  991. del _tensor_data_substitution_dict[self.metric]
  992. @deprecated(
  993. """
  994. The TensorIndexType.get_kronecker_delta() method is deprecated. Use
  995. the TensorIndexType.delta attribute instead.
  996. """,
  997. deprecated_since_version="1.5",
  998. active_deprecations_target="deprecated-tensorindextype-methods",
  999. )
  1000. def get_kronecker_delta(self):
  1001. sym2 = TensorSymmetry(get_symmetric_group_sgs(2))
  1002. delta = TensorHead('KD', [self]*2, sym2)
  1003. return delta
  1004. @deprecated(
  1005. """
  1006. The TensorIndexType.get_epsilon() method is deprecated. Use
  1007. the TensorIndexType.epsilon attribute instead.
  1008. """,
  1009. deprecated_since_version="1.5",
  1010. active_deprecations_target="deprecated-tensorindextype-methods",
  1011. )
  1012. def get_epsilon(self):
  1013. if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)):
  1014. return None
  1015. sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1))
  1016. epsilon = TensorHead('Eps', [self]*self._eps_dim, sym)
  1017. return epsilon
  1018. def _components_data_full_destroy(self):
  1019. """
  1020. EXPERIMENTAL: do not rely on this API method.
  1021. This destroys components data associated to the ``TensorIndexType``, if
  1022. any, specifically:
  1023. * metric tensor data
  1024. * Kronecker tensor data
  1025. """
  1026. if self in _tensor_data_substitution_dict:
  1027. del _tensor_data_substitution_dict[self]
  1028. def delete_tensmul_data(key):
  1029. if key in _tensor_data_substitution_dict._substitutions_dict_tensmul:
  1030. del _tensor_data_substitution_dict._substitutions_dict_tensmul[key]
  1031. # delete metric data:
  1032. delete_tensmul_data((self.metric, True, True))
  1033. delete_tensmul_data((self.metric, True, False))
  1034. delete_tensmul_data((self.metric, False, True))
  1035. delete_tensmul_data((self.metric, False, False))
  1036. # delete delta tensor data:
  1037. delta = self.get_kronecker_delta()
  1038. if delta in _tensor_data_substitution_dict:
  1039. del _tensor_data_substitution_dict[delta]
  1040. class TensorIndex(Basic):
  1041. """
  1042. Represents a tensor index
  1043. Parameters
  1044. ==========
  1045. name : name of the index, or ``True`` if you want it to be automatically assigned
  1046. tensor_index_type : ``TensorIndexType`` of the index
  1047. is_up : flag for contravariant index (is_up=True by default)
  1048. Attributes
  1049. ==========
  1050. ``name``
  1051. ``tensor_index_type``
  1052. ``is_up``
  1053. Notes
  1054. =====
  1055. Tensor indices are contracted with the Einstein summation convention.
  1056. An index can be in contravariant or in covariant form; in the latter
  1057. case it is represented prepending a ``-`` to the index name. Adding
  1058. ``-`` to a covariant (is_up=False) index makes it contravariant.
  1059. Dummy indices have a name with head given by
  1060. ``tensor_inde_type.dummy_name`` with underscore and a number.
  1061. Similar to ``symbols`` multiple contravariant indices can be created
  1062. at once using ``tensor_indices(s, typ)``, where ``s`` is a string
  1063. of names.
  1064. Examples
  1065. ========
  1066. >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices
  1067. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1068. >>> mu = TensorIndex('mu', Lorentz, is_up=False)
  1069. >>> nu, rho = tensor_indices('nu, rho', Lorentz)
  1070. >>> A = TensorHead('A', [Lorentz, Lorentz])
  1071. >>> A(mu, nu)
  1072. A(-mu, nu)
  1073. >>> A(-mu, -rho)
  1074. A(mu, -rho)
  1075. >>> A(mu, -mu)
  1076. A(-L_0, L_0)
  1077. """
  1078. def __new__(cls, name, tensor_index_type, is_up=True):
  1079. if isinstance(name, str):
  1080. name_symbol = Symbol(name)
  1081. elif isinstance(name, Symbol):
  1082. name_symbol = name
  1083. elif name is True:
  1084. name = "_i{}".format(len(tensor_index_type._autogenerated))
  1085. name_symbol = Symbol(name)
  1086. tensor_index_type._autogenerated.append(name_symbol)
  1087. else:
  1088. raise ValueError("invalid name")
  1089. is_up = sympify(is_up)
  1090. return Basic.__new__(cls, name_symbol, tensor_index_type, is_up)
  1091. @property
  1092. def name(self):
  1093. return self.args[0].name
  1094. @property
  1095. def tensor_index_type(self):
  1096. return self.args[1]
  1097. @property
  1098. def is_up(self):
  1099. return self.args[2]
  1100. def _print(self):
  1101. s = self.name
  1102. if not self.is_up:
  1103. s = '-%s' % s
  1104. return s
  1105. def __lt__(self, other):
  1106. return ((self.tensor_index_type, self.name) <
  1107. (other.tensor_index_type, other.name))
  1108. def __neg__(self):
  1109. t1 = TensorIndex(self.name, self.tensor_index_type,
  1110. (not self.is_up))
  1111. return t1
  1112. def tensor_indices(s, typ):
  1113. """
  1114. Returns list of tensor indices given their names and their types.
  1115. Parameters
  1116. ==========
  1117. s : string of comma separated names of indices
  1118. typ : ``TensorIndexType`` of the indices
  1119. Examples
  1120. ========
  1121. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
  1122. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1123. >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
  1124. """
  1125. if isinstance(s, str):
  1126. a = [x.name for x in symbols(s, seq=True)]
  1127. else:
  1128. raise ValueError('expecting a string')
  1129. tilist = [TensorIndex(i, typ) for i in a]
  1130. if len(tilist) == 1:
  1131. return tilist[0]
  1132. return tilist
  1133. class TensorSymmetry(Basic):
  1134. """
  1135. Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric
  1136. index permutation). For the relevant terminology see ``tensor_can.py``
  1137. section of the combinatorics module.
  1138. Parameters
  1139. ==========
  1140. bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor
  1141. Attributes
  1142. ==========
  1143. ``base`` : base of the BSGS
  1144. ``generators`` : generators of the BSGS
  1145. ``rank`` : rank of the tensor
  1146. Notes
  1147. =====
  1148. A tensor can have an arbitrary monoterm symmetry provided by its BSGS.
  1149. Multiterm symmetries, like the cyclic symmetry of the Riemann tensor
  1150. (i.e., Bianchi identity), are not covered. See combinatorics module for
  1151. information on how to generate BSGS for a general index permutation group.
  1152. Simple symmetries can be generated using built-in methods.
  1153. See Also
  1154. ========
  1155. sympy.combinatorics.tensor_can.get_symmetric_group_sgs
  1156. Examples
  1157. ========
  1158. Define a symmetric tensor of rank 2
  1159. >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead
  1160. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1161. >>> sym = TensorSymmetry(get_symmetric_group_sgs(2))
  1162. >>> T = TensorHead('T', [Lorentz]*2, sym)
  1163. Note, that the same can also be done using built-in TensorSymmetry methods
  1164. >>> sym2 = TensorSymmetry.fully_symmetric(2)
  1165. >>> sym == sym2
  1166. True
  1167. """
  1168. def __new__(cls, *args, **kw_args):
  1169. if len(args) == 1:
  1170. base, generators = args[0]
  1171. elif len(args) == 2:
  1172. base, generators = args
  1173. else:
  1174. raise TypeError("bsgs required, either two separate parameters or one tuple")
  1175. if not isinstance(base, Tuple):
  1176. base = Tuple(*base)
  1177. if not isinstance(generators, Tuple):
  1178. generators = Tuple(*generators)
  1179. return Basic.__new__(cls, base, generators, **kw_args)
  1180. @property
  1181. def base(self):
  1182. return self.args[0]
  1183. @property
  1184. def generators(self):
  1185. return self.args[1]
  1186. @property
  1187. def rank(self):
  1188. return self.generators[0].size - 2
  1189. @classmethod
  1190. def fully_symmetric(cls, rank):
  1191. """
  1192. Returns a fully symmetric (antisymmetric if ``rank``<0)
  1193. TensorSymmetry object for ``abs(rank)`` indices.
  1194. """
  1195. if rank > 0:
  1196. bsgs = get_symmetric_group_sgs(rank, False)
  1197. elif rank < 0:
  1198. bsgs = get_symmetric_group_sgs(-rank, True)
  1199. elif rank == 0:
  1200. bsgs = ([], [Permutation(1)])
  1201. return TensorSymmetry(bsgs)
  1202. @classmethod
  1203. def direct_product(cls, *args):
  1204. """
  1205. Returns a TensorSymmetry object that is being a direct product of
  1206. fully (anti-)symmetric index permutation groups.
  1207. Notes
  1208. =====
  1209. Some examples for different values of ``(*args)``:
  1210. ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)``
  1211. ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)``
  1212. ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)``
  1213. ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting
  1214. ``(1, 1, 1)`` tensor with 3 indices without any symmetry
  1215. """
  1216. base, sgs = [], [Permutation(1)]
  1217. for arg in args:
  1218. if arg > 0:
  1219. bsgs2 = get_symmetric_group_sgs(arg, False)
  1220. elif arg < 0:
  1221. bsgs2 = get_symmetric_group_sgs(-arg, True)
  1222. else:
  1223. continue
  1224. base, sgs = bsgs_direct_product(base, sgs, *bsgs2)
  1225. return TensorSymmetry(base, sgs)
  1226. @classmethod
  1227. def riemann(cls):
  1228. """
  1229. Returns a monotorem symmetry of the Riemann tensor
  1230. """
  1231. return TensorSymmetry(riemann_bsgs)
  1232. @classmethod
  1233. def no_symmetry(cls, rank):
  1234. """
  1235. TensorSymmetry object for ``rank`` indices with no symmetry
  1236. """
  1237. return TensorSymmetry([], [Permutation(rank+1)])
  1238. @deprecated(
  1239. """
  1240. The tensorsymmetry() function is deprecated. Use the TensorSymmetry
  1241. constructor instead.
  1242. """,
  1243. deprecated_since_version="1.5",
  1244. active_deprecations_target="deprecated-tensorsymmetry",
  1245. )
  1246. def tensorsymmetry(*args):
  1247. """
  1248. Returns a ``TensorSymmetry`` object. This method is deprecated, use
  1249. ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead.
  1250. Explanation
  1251. ===========
  1252. One can represent a tensor with any monoterm slot symmetry group
  1253. using a BSGS.
  1254. ``args`` can be a BSGS
  1255. ``args[0]`` base
  1256. ``args[1]`` sgs
  1257. Usually tensors are in (direct products of) representations
  1258. of the symmetric group;
  1259. ``args`` can be a list of lists representing the shapes of Young tableaux
  1260. Notes
  1261. =====
  1262. For instance:
  1263. ``[[1]]`` vector
  1264. ``[[1]*n]`` symmetric tensor of rank ``n``
  1265. ``[[n]]`` antisymmetric tensor of rank ``n``
  1266. ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor
  1267. ``[[1],[1]]`` vector*vector
  1268. ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector
  1269. Notice that with the shape ``[2, 2]`` we associate only the monoterm
  1270. symmetries of the Riemann tensor; this is an abuse of notation,
  1271. since the shape ``[2, 2]`` corresponds usually to the irreducible
  1272. representation characterized by the monoterm symmetries and by the
  1273. cyclic symmetry.
  1274. """
  1275. from sympy.combinatorics import Permutation
  1276. def tableau2bsgs(a):
  1277. if len(a) == 1:
  1278. # antisymmetric vector
  1279. n = a[0]
  1280. bsgs = get_symmetric_group_sgs(n, 1)
  1281. else:
  1282. if all(x == 1 for x in a):
  1283. # symmetric vector
  1284. n = len(a)
  1285. bsgs = get_symmetric_group_sgs(n)
  1286. elif a == [2, 2]:
  1287. bsgs = riemann_bsgs
  1288. else:
  1289. raise NotImplementedError
  1290. return bsgs
  1291. if not args:
  1292. return TensorSymmetry(Tuple(), Tuple(Permutation(1)))
  1293. if len(args) == 2 and isinstance(args[1][0], Permutation):
  1294. return TensorSymmetry(args)
  1295. base, sgs = tableau2bsgs(args[0])
  1296. for a in args[1:]:
  1297. basex, sgsx = tableau2bsgs(a)
  1298. base, sgs = bsgs_direct_product(base, sgs, basex, sgsx)
  1299. return TensorSymmetry(Tuple(base, sgs))
  1300. @deprecated(
  1301. "TensorType is deprecated. Use tensor_heads() instead.",
  1302. deprecated_since_version="1.5",
  1303. active_deprecations_target="deprecated-tensortype",
  1304. )
  1305. class TensorType(Basic):
  1306. """
  1307. Class of tensor types. Deprecated, use tensor_heads() instead.
  1308. Parameters
  1309. ==========
  1310. index_types : list of ``TensorIndexType`` of the tensor indices
  1311. symmetry : ``TensorSymmetry`` of the tensor
  1312. Attributes
  1313. ==========
  1314. ``index_types``
  1315. ``symmetry``
  1316. ``types`` : list of ``TensorIndexType`` without repetitions
  1317. """
  1318. is_commutative = False
  1319. def __new__(cls, index_types, symmetry, **kw_args):
  1320. assert symmetry.rank == len(index_types)
  1321. obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args)
  1322. return obj
  1323. @property
  1324. def index_types(self):
  1325. return self.args[0]
  1326. @property
  1327. def symmetry(self):
  1328. return self.args[1]
  1329. @property
  1330. def types(self):
  1331. return sorted(set(self.index_types), key=lambda x: x.name)
  1332. def __str__(self):
  1333. return 'TensorType(%s)' % ([str(x) for x in self.index_types])
  1334. def __call__(self, s, comm=0):
  1335. """
  1336. Return a TensorHead object or a list of TensorHead objects.
  1337. Parameters
  1338. ==========
  1339. s : name or string of names.
  1340. comm : Commutation group.
  1341. see ``_TensorManager.set_comm``
  1342. """
  1343. if isinstance(s, str):
  1344. names = [x.name for x in symbols(s, seq=True)]
  1345. else:
  1346. raise ValueError('expecting a string')
  1347. if len(names) == 1:
  1348. return TensorHead(names[0], self.index_types, self.symmetry, comm)
  1349. else:
  1350. return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names]
  1351. @deprecated(
  1352. """
  1353. The tensorhead() function is deprecated. Use tensor_heads() instead.
  1354. """,
  1355. deprecated_since_version="1.5",
  1356. active_deprecations_target="deprecated-tensorhead",
  1357. )
  1358. def tensorhead(name, typ, sym=None, comm=0):
  1359. """
  1360. Function generating tensorhead(s). This method is deprecated,
  1361. use TensorHead constructor or tensor_heads() instead.
  1362. Parameters
  1363. ==========
  1364. name : name or sequence of names (as in ``symbols``)
  1365. typ : index types
  1366. sym : same as ``*args`` in ``tensorsymmetry``
  1367. comm : commutation group number
  1368. see ``_TensorManager.set_comm``
  1369. """
  1370. if sym is None:
  1371. sym = [[1] for i in range(len(typ))]
  1372. with ignore_warnings(SymPyDeprecationWarning):
  1373. sym = tensorsymmetry(*sym)
  1374. return TensorHead(name, typ, sym, comm)
  1375. class TensorHead(Basic):
  1376. """
  1377. Tensor head of the tensor.
  1378. Parameters
  1379. ==========
  1380. name : name of the tensor
  1381. index_types : list of TensorIndexType
  1382. symmetry : TensorSymmetry of the tensor
  1383. comm : commutation group number
  1384. Attributes
  1385. ==========
  1386. ``name``
  1387. ``index_types``
  1388. ``rank`` : total number of indices
  1389. ``symmetry``
  1390. ``comm`` : commutation group
  1391. Notes
  1392. =====
  1393. Similar to ``symbols`` multiple TensorHeads can be created using
  1394. ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s``
  1395. is the string of names and ``sym`` is the monoterm tensor symmetry
  1396. (see ``tensorsymmetry``).
  1397. A ``TensorHead`` belongs to a commutation group, defined by a
  1398. symbol on number ``comm`` (see ``_TensorManager.set_comm``);
  1399. tensors in a commutation group have the same commutation properties;
  1400. by default ``comm`` is ``0``, the group of the commuting tensors.
  1401. Examples
  1402. ========
  1403. Define a fully antisymmetric tensor of rank 2:
  1404. >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
  1405. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1406. >>> asym2 = TensorSymmetry.fully_symmetric(-2)
  1407. >>> A = TensorHead('A', [Lorentz, Lorentz], asym2)
  1408. Examples with ndarray values, the components data assigned to the
  1409. ``TensorHead`` object are assumed to be in a fully-contravariant
  1410. representation. In case it is necessary to assign components data which
  1411. represents the values of a non-fully covariant tensor, see the other
  1412. examples.
  1413. >>> from sympy.tensor.tensor import tensor_indices
  1414. >>> from sympy import diag
  1415. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1416. >>> i0, i1 = tensor_indices('i0:2', Lorentz)
  1417. Specify a replacement dictionary to keep track of the arrays to use for
  1418. replacements in the tensorial expression. The ``TensorIndexType`` is
  1419. associated to the metric used for contractions (in fully covariant form):
  1420. >>> repl = {Lorentz: diag(1, -1, -1, -1)}
  1421. Let's see some examples of working with components with the electromagnetic
  1422. tensor:
  1423. >>> from sympy import symbols
  1424. >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
  1425. >>> c = symbols('c', positive=True)
  1426. Let's define `F`, an antisymmetric tensor:
  1427. >>> F = TensorHead('F', [Lorentz, Lorentz], asym2)
  1428. Let's update the dictionary to contain the matrix to use in the
  1429. replacements:
  1430. >>> repl.update({F(-i0, -i1): [
  1431. ... [0, Ex/c, Ey/c, Ez/c],
  1432. ... [-Ex/c, 0, -Bz, By],
  1433. ... [-Ey/c, Bz, 0, -Bx],
  1434. ... [-Ez/c, -By, Bx, 0]]})
  1435. Now it is possible to retrieve the contravariant form of the Electromagnetic
  1436. tensor:
  1437. >>> F(i0, i1).replace_with_arrays(repl, [i0, i1])
  1438. [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]]
  1439. and the mixed contravariant-covariant form:
  1440. >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1])
  1441. [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]]
  1442. Energy-momentum of a particle may be represented as:
  1443. >>> from sympy import symbols
  1444. >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1))
  1445. >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True)
  1446. >>> repl.update({P(i0): [E, px, py, pz]})
  1447. The contravariant and covariant components are, respectively:
  1448. >>> P(i0).replace_with_arrays(repl, [i0])
  1449. [E, p_x, p_y, p_z]
  1450. >>> P(-i0).replace_with_arrays(repl, [-i0])
  1451. [E, -p_x, -p_y, -p_z]
  1452. The contraction of a 1-index tensor by itself:
  1453. >>> expr = P(i0)*P(-i0)
  1454. >>> expr.replace_with_arrays(repl, [])
  1455. E**2 - p_x**2 - p_y**2 - p_z**2
  1456. """
  1457. is_commutative = False
  1458. def __new__(cls, name, index_types, symmetry=None, comm=0):
  1459. if isinstance(name, str):
  1460. name_symbol = Symbol(name)
  1461. elif isinstance(name, Symbol):
  1462. name_symbol = name
  1463. else:
  1464. raise ValueError("invalid name")
  1465. if symmetry is None:
  1466. symmetry = TensorSymmetry.no_symmetry(len(index_types))
  1467. else:
  1468. assert symmetry.rank == len(index_types)
  1469. obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry)
  1470. obj.comm = TensorManager.comm_symbols2i(comm)
  1471. return obj
  1472. @property
  1473. def name(self):
  1474. return self.args[0].name
  1475. @property
  1476. def index_types(self):
  1477. return list(self.args[1])
  1478. @property
  1479. def symmetry(self):
  1480. return self.args[2]
  1481. @property
  1482. def rank(self):
  1483. return len(self.index_types)
  1484. def __lt__(self, other):
  1485. return (self.name, self.index_types) < (other.name, other.index_types)
  1486. def commutes_with(self, other):
  1487. """
  1488. Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute.
  1489. Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute.
  1490. """
  1491. r = TensorManager.get_comm(self.comm, other.comm)
  1492. return r
  1493. def _print(self):
  1494. return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types]))
  1495. def __call__(self, *indices, **kw_args):
  1496. """
  1497. Returns a tensor with indices.
  1498. Explanation
  1499. ===========
  1500. There is a special behavior in case of indices denoted by ``True``,
  1501. they are considered auto-matrix indices, their slots are automatically
  1502. filled, and confer to the tensor the behavior of a matrix or vector
  1503. upon multiplication with another tensor containing auto-matrix indices
  1504. of the same ``TensorIndexType``. This means indices get summed over the
  1505. same way as in matrix multiplication. For matrix behavior, define two
  1506. auto-matrix indices, for vector behavior define just one.
  1507. Indices can also be strings, in which case the attribute
  1508. ``index_types`` is used to convert them to proper ``TensorIndex``.
  1509. Examples
  1510. ========
  1511. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead
  1512. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1513. >>> a, b = tensor_indices('a,b', Lorentz)
  1514. >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
  1515. >>> t = A(a, -b)
  1516. >>> t
  1517. A(a, -b)
  1518. """
  1519. updated_indices = []
  1520. for idx, typ in zip(indices, self.index_types):
  1521. if isinstance(idx, str):
  1522. idx = idx.strip().replace(" ", "")
  1523. if idx.startswith('-'):
  1524. updated_indices.append(TensorIndex(idx[1:], typ,
  1525. is_up=False))
  1526. else:
  1527. updated_indices.append(TensorIndex(idx, typ))
  1528. else:
  1529. updated_indices.append(idx)
  1530. updated_indices += indices[len(updated_indices):]
  1531. tensor = Tensor(self, updated_indices, **kw_args)
  1532. return tensor.doit()
  1533. # Everything below this line is deprecated
  1534. def __pow__(self, other):
  1535. deprecate_data()
  1536. with ignore_warnings(SymPyDeprecationWarning):
  1537. if self.data is None:
  1538. raise ValueError("No power on abstract tensors.")
  1539. from .array import tensorproduct, tensorcontraction
  1540. metrics = [_.data for _ in self.index_types]
  1541. marray = self.data
  1542. marraydim = marray.rank()
  1543. for metric in metrics:
  1544. marray = tensorproduct(marray, metric, marray)
  1545. marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2))
  1546. return marray ** (other * S.Half)
  1547. @property
  1548. def data(self):
  1549. deprecate_data()
  1550. with ignore_warnings(SymPyDeprecationWarning):
  1551. return _tensor_data_substitution_dict[self]
  1552. @data.setter
  1553. def data(self, data):
  1554. deprecate_data()
  1555. with ignore_warnings(SymPyDeprecationWarning):
  1556. _tensor_data_substitution_dict[self] = data
  1557. @data.deleter
  1558. def data(self):
  1559. deprecate_data()
  1560. if self in _tensor_data_substitution_dict:
  1561. del _tensor_data_substitution_dict[self]
  1562. def __iter__(self):
  1563. deprecate_data()
  1564. with ignore_warnings(SymPyDeprecationWarning):
  1565. return self.data.__iter__()
  1566. def _components_data_full_destroy(self):
  1567. """
  1568. EXPERIMENTAL: do not rely on this API method.
  1569. Destroy components data associated to the ``TensorHead`` object, this
  1570. checks for attached components data, and destroys components data too.
  1571. """
  1572. # do not garbage collect Kronecker tensor (it should be done by
  1573. # ``TensorIndexType`` garbage collection)
  1574. deprecate_data()
  1575. if self.name == "KD":
  1576. return
  1577. # the data attached to a tensor must be deleted only by the TensorHead
  1578. # destructor. If the TensorHead is deleted, it means that there are no
  1579. # more instances of that tensor anywhere.
  1580. if self in _tensor_data_substitution_dict:
  1581. del _tensor_data_substitution_dict[self]
  1582. def tensor_heads(s, index_types, symmetry=None, comm=0):
  1583. """
  1584. Returns a sequence of TensorHeads from a string `s`
  1585. """
  1586. if isinstance(s, str):
  1587. names = [x.name for x in symbols(s, seq=True)]
  1588. else:
  1589. raise ValueError('expecting a string')
  1590. thlist = [TensorHead(name, index_types, symmetry, comm) for name in names]
  1591. if len(thlist) == 1:
  1592. return thlist[0]
  1593. return thlist
  1594. class _TensorMetaclass(ManagedProperties, ABCMeta):
  1595. pass
  1596. class TensExpr(Expr, metaclass=_TensorMetaclass):
  1597. """
  1598. Abstract base class for tensor expressions
  1599. Notes
  1600. =====
  1601. A tensor expression is an expression formed by tensors;
  1602. currently the sums of tensors are distributed.
  1603. A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``.
  1604. ``TensMul`` objects are formed by products of component tensors,
  1605. and include a coefficient, which is a SymPy expression.
  1606. In the internal representation contracted indices are represented
  1607. by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position
  1608. of the component tensor with contravariant index, ``ipos1`` is the
  1609. slot which the index occupies in that component tensor.
  1610. Contracted indices are therefore nameless in the internal representation.
  1611. """
  1612. _op_priority = 12.0
  1613. is_commutative = False
  1614. def __neg__(self):
  1615. return self*S.NegativeOne
  1616. def __abs__(self):
  1617. raise NotImplementedError
  1618. def __add__(self, other):
  1619. return TensAdd(self, other).doit()
  1620. def __radd__(self, other):
  1621. return TensAdd(other, self).doit()
  1622. def __sub__(self, other):
  1623. return TensAdd(self, -other).doit()
  1624. def __rsub__(self, other):
  1625. return TensAdd(other, -self).doit()
  1626. def __mul__(self, other):
  1627. """
  1628. Multiply two tensors using Einstein summation convention.
  1629. Explanation
  1630. ===========
  1631. If the two tensors have an index in common, one contravariant
  1632. and the other covariant, in their product the indices are summed
  1633. Examples
  1634. ========
  1635. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  1636. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1637. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  1638. >>> g = Lorentz.metric
  1639. >>> p, q = tensor_heads('p,q', [Lorentz])
  1640. >>> t1 = p(m0)
  1641. >>> t2 = q(-m0)
  1642. >>> t1*t2
  1643. p(L_0)*q(-L_0)
  1644. """
  1645. return TensMul(self, other).doit()
  1646. def __rmul__(self, other):
  1647. return TensMul(other, self).doit()
  1648. def __truediv__(self, other):
  1649. other = _sympify(other)
  1650. if isinstance(other, TensExpr):
  1651. raise ValueError('cannot divide by a tensor')
  1652. return TensMul(self, S.One/other).doit()
  1653. def __rtruediv__(self, other):
  1654. raise ValueError('cannot divide by a tensor')
  1655. def __pow__(self, other):
  1656. deprecate_data()
  1657. with ignore_warnings(SymPyDeprecationWarning):
  1658. if self.data is None:
  1659. raise ValueError("No power without ndarray data.")
  1660. from .array import tensorproduct, tensorcontraction
  1661. free = self.free
  1662. marray = self.data
  1663. mdim = marray.rank()
  1664. for metric in free:
  1665. marray = tensorcontraction(
  1666. tensorproduct(
  1667. marray,
  1668. metric[0].tensor_index_type.data,
  1669. marray),
  1670. (0, mdim), (mdim+1, mdim+2)
  1671. )
  1672. return marray ** (other * S.Half)
  1673. def __rpow__(self, other):
  1674. raise NotImplementedError
  1675. @property
  1676. @abstractmethod
  1677. def nocoeff(self):
  1678. raise NotImplementedError("abstract method")
  1679. @property
  1680. @abstractmethod
  1681. def coeff(self):
  1682. raise NotImplementedError("abstract method")
  1683. @abstractmethod
  1684. def get_indices(self):
  1685. raise NotImplementedError("abstract method")
  1686. @abstractmethod
  1687. def get_free_indices(self): # type: () -> List[TensorIndex]
  1688. raise NotImplementedError("abstract method")
  1689. @abstractmethod
  1690. def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr
  1691. raise NotImplementedError("abstract method")
  1692. def fun_eval(self, *index_tuples):
  1693. deprecate_fun_eval()
  1694. return self.substitute_indices(*index_tuples)
  1695. def get_matrix(self):
  1696. """
  1697. DEPRECATED: do not use.
  1698. Returns ndarray components data as a matrix, if components data are
  1699. available and ndarray dimension does not exceed 2.
  1700. """
  1701. from sympy.matrices.dense import Matrix
  1702. deprecate_data()
  1703. with ignore_warnings(SymPyDeprecationWarning):
  1704. if 0 < self.rank <= 2:
  1705. rows = self.data.shape[0]
  1706. columns = self.data.shape[1] if self.rank == 2 else 1
  1707. if self.rank == 2:
  1708. mat_list = [] * rows
  1709. for i in range(rows):
  1710. mat_list.append([])
  1711. for j in range(columns):
  1712. mat_list[i].append(self[i, j])
  1713. else:
  1714. mat_list = [None] * rows
  1715. for i in range(rows):
  1716. mat_list[i] = self[i]
  1717. return Matrix(mat_list)
  1718. else:
  1719. raise NotImplementedError(
  1720. "missing multidimensional reduction to matrix.")
  1721. @staticmethod
  1722. def _get_indices_permutation(indices1, indices2):
  1723. return [indices1.index(i) for i in indices2]
  1724. def expand(self, **hints):
  1725. return _expand(self, **hints).doit()
  1726. def _expand(self, **kwargs):
  1727. return self
  1728. def _get_free_indices_set(self):
  1729. indset = set()
  1730. for arg in self.args:
  1731. if isinstance(arg, TensExpr):
  1732. indset.update(arg._get_free_indices_set())
  1733. return indset
  1734. def _get_dummy_indices_set(self):
  1735. indset = set()
  1736. for arg in self.args:
  1737. if isinstance(arg, TensExpr):
  1738. indset.update(arg._get_dummy_indices_set())
  1739. return indset
  1740. def _get_indices_set(self):
  1741. indset = set()
  1742. for arg in self.args:
  1743. if isinstance(arg, TensExpr):
  1744. indset.update(arg._get_indices_set())
  1745. return indset
  1746. @property
  1747. def _iterate_dummy_indices(self):
  1748. dummy_set = self._get_dummy_indices_set()
  1749. def recursor(expr, pos):
  1750. if isinstance(expr, TensorIndex):
  1751. if expr in dummy_set:
  1752. yield (expr, pos)
  1753. elif isinstance(expr, (Tuple, TensExpr)):
  1754. for p, arg in enumerate(expr.args):
  1755. yield from recursor(arg, pos+(p,))
  1756. return recursor(self, ())
  1757. @property
  1758. def _iterate_free_indices(self):
  1759. free_set = self._get_free_indices_set()
  1760. def recursor(expr, pos):
  1761. if isinstance(expr, TensorIndex):
  1762. if expr in free_set:
  1763. yield (expr, pos)
  1764. elif isinstance(expr, (Tuple, TensExpr)):
  1765. for p, arg in enumerate(expr.args):
  1766. yield from recursor(arg, pos+(p,))
  1767. return recursor(self, ())
  1768. @property
  1769. def _iterate_indices(self):
  1770. def recursor(expr, pos):
  1771. if isinstance(expr, TensorIndex):
  1772. yield (expr, pos)
  1773. elif isinstance(expr, (Tuple, TensExpr)):
  1774. for p, arg in enumerate(expr.args):
  1775. yield from recursor(arg, pos+(p,))
  1776. return recursor(self, ())
  1777. @staticmethod
  1778. def _contract_and_permute_with_metric(metric, array, pos, dim):
  1779. # TODO: add possibility of metric after (spinors)
  1780. from .array import tensorcontraction, tensorproduct, permutedims
  1781. array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))
  1782. permu = list(range(dim))
  1783. permu[0], permu[pos] = permu[pos], permu[0]
  1784. return permutedims(array, permu)
  1785. @staticmethod
  1786. def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):
  1787. from .array import permutedims
  1788. index_types1 = [i.tensor_index_type for i in free_ind1]
  1789. # Check if variance of indices needs to be fixed:
  1790. pos2up = []
  1791. pos2down = []
  1792. free2remaining = free_ind2[:]
  1793. for pos1, index1 in enumerate(free_ind1):
  1794. if index1 in free2remaining:
  1795. pos2 = free2remaining.index(index1)
  1796. free2remaining[pos2] = None
  1797. continue
  1798. if -index1 in free2remaining:
  1799. pos2 = free2remaining.index(-index1)
  1800. free2remaining[pos2] = None
  1801. free_ind2[pos2] = index1
  1802. if index1.is_up:
  1803. pos2up.append(pos2)
  1804. else:
  1805. pos2down.append(pos2)
  1806. else:
  1807. index2 = free2remaining[pos1]
  1808. if index2 is None:
  1809. raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
  1810. free2remaining[pos1] = None
  1811. free_ind2[pos1] = index1
  1812. if index1.is_up ^ index2.is_up:
  1813. if index1.is_up:
  1814. pos2up.append(pos1)
  1815. else:
  1816. pos2down.append(pos1)
  1817. if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):
  1818. raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2))
  1819. # Raise indices:
  1820. for pos in pos2up:
  1821. index_type_pos = index_types1[pos] # type: TensorIndexType
  1822. if index_type_pos not in replacement_dict:
  1823. raise ValueError("No metric provided to lower index")
  1824. metric = replacement_dict[index_type_pos]
  1825. metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)
  1826. array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))
  1827. # Lower indices:
  1828. for pos in pos2down:
  1829. index_type_pos = index_types1[pos] # type: TensorIndexType
  1830. if index_type_pos not in replacement_dict:
  1831. raise ValueError("No metric provided to lower index")
  1832. metric = replacement_dict[index_type_pos]
  1833. array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))
  1834. if free_ind1:
  1835. permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)
  1836. array = permutedims(array, permutation)
  1837. if hasattr(array, "rank") and array.rank() == 0:
  1838. array = array[()]
  1839. return free_ind2, array
  1840. def replace_with_arrays(self, replacement_dict, indices=None):
  1841. """
  1842. Replace the tensorial expressions with arrays. The final array will
  1843. correspond to the N-dimensional array with indices arranged according
  1844. to ``indices``.
  1845. Parameters
  1846. ==========
  1847. replacement_dict
  1848. dictionary containing the replacement rules for tensors.
  1849. indices
  1850. the index order with respect to which the array is read. The
  1851. original index order will be used if no value is passed.
  1852. Examples
  1853. ========
  1854. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices
  1855. >>> from sympy.tensor.tensor import TensorHead
  1856. >>> from sympy import symbols, diag
  1857. >>> L = TensorIndexType("L")
  1858. >>> i, j = tensor_indices("i j", L)
  1859. >>> A = TensorHead("A", [L])
  1860. >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i])
  1861. [1, 2]
  1862. Since 'indices' is optional, we can also call replace_with_arrays by
  1863. this way if no specific index order is needed:
  1864. >>> A(i).replace_with_arrays({A(i): [1, 2]})
  1865. [1, 2]
  1866. >>> expr = A(i)*A(j)
  1867. >>> expr.replace_with_arrays({A(i): [1, 2]})
  1868. [[1, 2], [2, 4]]
  1869. For contractions, specify the metric of the ``TensorIndexType``, which
  1870. in this case is ``L``, in its covariant form:
  1871. >>> expr = A(i)*A(-i)
  1872. >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)})
  1873. -3
  1874. Symmetrization of an array:
  1875. >>> H = TensorHead("H", [L, L])
  1876. >>> a, b, c, d = symbols("a b c d")
  1877. >>> expr = H(i, j)/2 + H(j, i)/2
  1878. >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]})
  1879. [[a, b/2 + c/2], [b/2 + c/2, d]]
  1880. Anti-symmetrization of an array:
  1881. >>> expr = H(i, j)/2 - H(j, i)/2
  1882. >>> repl = {H(i, j): [[a, b], [c, d]]}
  1883. >>> expr.replace_with_arrays(repl)
  1884. [[0, b/2 - c/2], [-b/2 + c/2, 0]]
  1885. The same expression can be read as the transpose by inverting ``i`` and
  1886. ``j``:
  1887. >>> expr.replace_with_arrays(repl, [j, i])
  1888. [[0, -b/2 + c/2], [b/2 - c/2, 0]]
  1889. """
  1890. from .array import Array
  1891. indices = indices or []
  1892. replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()}
  1893. # Check dimensions of replaced arrays:
  1894. for tensor, array in replacement_dict.items():
  1895. if isinstance(tensor, TensorIndexType):
  1896. expected_shape = [tensor.dim for i in range(2)]
  1897. else:
  1898. expected_shape = [index_type.dim for index_type in tensor.index_types]
  1899. if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if
  1900. dim1.is_number else True for dim1, dim2 in zip(expected_shape,
  1901. array.shape))):
  1902. raise ValueError("shapes for tensor %s expected to be %s, "\
  1903. "replacement array shape is %s" % (tensor, expected_shape,
  1904. array.shape))
  1905. ret_indices, array = self._extract_data(replacement_dict)
  1906. last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict)
  1907. return array
  1908. def _check_add_Sum(self, expr, index_symbols):
  1909. from sympy.concrete.summations import Sum
  1910. indices = self.get_indices()
  1911. dum = self.dum
  1912. sum_indices = [ (index_symbols[i], 0,
  1913. indices[i].tensor_index_type.dim-1) for i, j in dum]
  1914. if sum_indices:
  1915. expr = Sum(expr, *sum_indices)
  1916. return expr
  1917. def _expand_partial_derivative(self):
  1918. # simply delegate the _expand_partial_derivative() to
  1919. # its arguments to expand a possibly found PartialDerivative
  1920. return self.func(*[
  1921. a._expand_partial_derivative()
  1922. if isinstance(a, TensExpr) else a
  1923. for a in self.args])
  1924. class TensAdd(TensExpr, AssocOp):
  1925. """
  1926. Sum of tensors.
  1927. Parameters
  1928. ==========
  1929. free_args : list of the free indices
  1930. Attributes
  1931. ==========
  1932. ``args`` : tuple of addends
  1933. ``rank`` : rank of the tensor
  1934. ``free_args`` : list of the free indices in sorted order
  1935. Examples
  1936. ========
  1937. >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices
  1938. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  1939. >>> a, b = tensor_indices('a,b', Lorentz)
  1940. >>> p, q = tensor_heads('p,q', [Lorentz])
  1941. >>> t = p(a) + q(a); t
  1942. p(a) + q(a)
  1943. Examples with components data added to the tensor expression:
  1944. >>> from sympy import symbols, diag
  1945. >>> x, y, z, t = symbols("x y z t")
  1946. >>> repl = {}
  1947. >>> repl[Lorentz] = diag(1, -1, -1, -1)
  1948. >>> repl[p(a)] = [1, 2, 3, 4]
  1949. >>> repl[q(a)] = [x, y, z, t]
  1950. The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58
  1951. >>> expr = p(a) + q(a)
  1952. >>> expr.replace_with_arrays(repl, [a])
  1953. [x + 1, y + 2, z + 3, t + 4]
  1954. """
  1955. def __new__(cls, *args, **kw_args):
  1956. args = [_sympify(x) for x in args if x]
  1957. args = TensAdd._tensAdd_flatten(args)
  1958. args.sort(key=default_sort_key)
  1959. if not args:
  1960. return S.Zero
  1961. if len(args) == 1:
  1962. return args[0]
  1963. return Basic.__new__(cls, *args, **kw_args)
  1964. @property
  1965. def coeff(self):
  1966. return S.One
  1967. @property
  1968. def nocoeff(self):
  1969. return self
  1970. def get_free_indices(self): # type: () -> List[TensorIndex]
  1971. return self.free_indices
  1972. def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr
  1973. newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]
  1974. return self.func(*newargs)
  1975. @memoize_property
  1976. def rank(self):
  1977. if isinstance(self.args[0], TensExpr):
  1978. return self.args[0].rank
  1979. else:
  1980. return 0
  1981. @memoize_property
  1982. def free_args(self):
  1983. if isinstance(self.args[0], TensExpr):
  1984. return self.args[0].free_args
  1985. else:
  1986. return []
  1987. @memoize_property
  1988. def free_indices(self):
  1989. if isinstance(self.args[0], TensExpr):
  1990. return self.args[0].get_free_indices()
  1991. else:
  1992. return set()
  1993. def doit(self, **kwargs):
  1994. deep = kwargs.get('deep', True)
  1995. if deep:
  1996. args = [arg.doit(**kwargs) for arg in self.args]
  1997. else:
  1998. args = self.args
  1999. if not args:
  2000. return S.Zero
  2001. if len(args) == 1 and not isinstance(args[0], TensExpr):
  2002. return args[0]
  2003. # now check that all addends have the same indices:
  2004. TensAdd._tensAdd_check(args)
  2005. # if TensAdd has only 1 element in its `args`:
  2006. if len(args) == 1: # and isinstance(args[0], TensMul):
  2007. return args[0]
  2008. # Remove zeros:
  2009. args = [x for x in args if x]
  2010. # if there are no more args (i.e. have cancelled out),
  2011. # just return zero:
  2012. if not args:
  2013. return S.Zero
  2014. if len(args) == 1:
  2015. return args[0]
  2016. # Collect terms appearing more than once, differing by their coefficients:
  2017. args = TensAdd._tensAdd_collect_terms(args)
  2018. # collect canonicalized terms
  2019. def sort_key(t):
  2020. if not isinstance(t, TensExpr):
  2021. return [], [], []
  2022. if hasattr(t, "_index_structure") and hasattr(t, "components"):
  2023. x = get_index_structure(t)
  2024. return t.components, x.free, x.dum
  2025. return [], [], []
  2026. args.sort(key=sort_key)
  2027. if not args:
  2028. return S.Zero
  2029. # it there is only a component tensor return it
  2030. if len(args) == 1:
  2031. return args[0]
  2032. obj = self.func(*args)
  2033. return obj
  2034. @staticmethod
  2035. def _tensAdd_flatten(args):
  2036. # flatten TensAdd, coerce terms which are not tensors to tensors
  2037. a = []
  2038. for x in args:
  2039. if isinstance(x, (Add, TensAdd)):
  2040. a.extend(list(x.args))
  2041. else:
  2042. a.append(x)
  2043. args = [x for x in a if x.coeff]
  2044. return args
  2045. @staticmethod
  2046. def _tensAdd_check(args):
  2047. # check that all addends have the same free indices
  2048. def get_indices_set(x): # type: (Expr) -> tSet[TensorIndex]
  2049. if isinstance(x, TensExpr):
  2050. return set(x.get_free_indices())
  2051. return set()
  2052. indices0 = get_indices_set(args[0]) # type: tSet[TensorIndex]
  2053. list_indices = [get_indices_set(arg) for arg in args[1:]] # type: List[tSet[TensorIndex]]
  2054. if not all(x == indices0 for x in list_indices):
  2055. raise ValueError('all tensors must have the same indices')
  2056. @staticmethod
  2057. def _tensAdd_collect_terms(args):
  2058. # collect TensMul terms differing at most by their coefficient
  2059. terms_dict = defaultdict(list)
  2060. scalars = S.Zero
  2061. if isinstance(args[0], TensExpr):
  2062. free_indices = set(args[0].get_free_indices())
  2063. else:
  2064. free_indices = set()
  2065. for arg in args:
  2066. if not isinstance(arg, TensExpr):
  2067. if free_indices != set():
  2068. raise ValueError("wrong valence")
  2069. scalars += arg
  2070. continue
  2071. if free_indices != set(arg.get_free_indices()):
  2072. raise ValueError("wrong valence")
  2073. # TODO: what is the part which is not a coeff?
  2074. # needs an implementation similar to .as_coeff_Mul()
  2075. terms_dict[arg.nocoeff].append(arg.coeff)
  2076. new_args = [TensMul(Add(*coeff), t).doit() for t, coeff in terms_dict.items() if Add(*coeff) != 0]
  2077. if isinstance(scalars, Add):
  2078. new_args = list(scalars.args) + new_args
  2079. elif scalars != 0:
  2080. new_args = [scalars] + new_args
  2081. return new_args
  2082. def get_indices(self):
  2083. indices = []
  2084. for arg in self.args:
  2085. indices.extend([i for i in get_indices(arg) if i not in indices])
  2086. return indices
  2087. def _expand(self, **hints):
  2088. return TensAdd(*[_expand(i, **hints) for i in self.args])
  2089. def __call__(self, *indices):
  2090. deprecate_call()
  2091. free_args = self.free_args
  2092. indices = list(indices)
  2093. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  2094. raise ValueError('incompatible types')
  2095. if indices == free_args:
  2096. return self
  2097. index_tuples = list(zip(free_args, indices))
  2098. a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args]
  2099. res = TensAdd(*a).doit()
  2100. return res
  2101. def canon_bp(self):
  2102. """
  2103. Canonicalize using the Butler-Portugal algorithm for canonicalization
  2104. under monoterm symmetries.
  2105. """
  2106. expr = self.expand()
  2107. args = [canon_bp(x) for x in expr.args]
  2108. res = TensAdd(*args).doit()
  2109. return res
  2110. def equals(self, other):
  2111. other = _sympify(other)
  2112. if isinstance(other, TensMul) and other.coeff == 0:
  2113. return all(x.coeff == 0 for x in self.args)
  2114. if isinstance(other, TensExpr):
  2115. if self.rank != other.rank:
  2116. return False
  2117. if isinstance(other, TensAdd):
  2118. if set(self.args) != set(other.args):
  2119. return False
  2120. else:
  2121. return True
  2122. t = self - other
  2123. if not isinstance(t, TensExpr):
  2124. return t == 0
  2125. else:
  2126. if isinstance(t, TensMul):
  2127. return t.coeff == 0
  2128. else:
  2129. return all(x.coeff == 0 for x in t.args)
  2130. def __getitem__(self, item):
  2131. deprecate_data()
  2132. with ignore_warnings(SymPyDeprecationWarning):
  2133. return self.data[item]
  2134. def contract_delta(self, delta):
  2135. args = [x.contract_delta(delta) for x in self.args]
  2136. t = TensAdd(*args).doit()
  2137. return canon_bp(t)
  2138. def contract_metric(self, g):
  2139. """
  2140. Raise or lower indices with the metric ``g``.
  2141. Parameters
  2142. ==========
  2143. g : metric
  2144. contract_all : if True, eliminate all ``g`` which are contracted
  2145. Notes
  2146. =====
  2147. see the ``TensorIndexType`` docstring for the contraction conventions
  2148. """
  2149. args = [contract_metric(x, g) for x in self.args]
  2150. t = TensAdd(*args).doit()
  2151. return canon_bp(t)
  2152. def substitute_indices(self, *index_tuples):
  2153. new_args = []
  2154. for arg in self.args:
  2155. if isinstance(arg, TensExpr):
  2156. arg = arg.substitute_indices(*index_tuples)
  2157. new_args.append(arg)
  2158. return TensAdd(*new_args).doit()
  2159. def _print(self):
  2160. a = []
  2161. args = self.args
  2162. for x in args:
  2163. a.append(str(x))
  2164. s = ' + '.join(a)
  2165. s = s.replace('+ -', '- ')
  2166. return s
  2167. def _extract_data(self, replacement_dict):
  2168. from sympy.tensor.array import Array, permutedims
  2169. args_indices, arrays = zip(*[
  2170. arg._extract_data(replacement_dict) if
  2171. isinstance(arg, TensExpr) else ([], arg) for arg in self.args
  2172. ])
  2173. arrays = [Array(i) for i in arrays]
  2174. ref_indices = args_indices[0]
  2175. for i in range(1, len(args_indices)):
  2176. indices = args_indices[i]
  2177. array = arrays[i]
  2178. permutation = TensMul._get_indices_permutation(indices, ref_indices)
  2179. arrays[i] = permutedims(array, permutation)
  2180. return ref_indices, sum(arrays, Array.zeros(*array.shape))
  2181. @property
  2182. def data(self):
  2183. deprecate_data()
  2184. with ignore_warnings(SymPyDeprecationWarning):
  2185. return _tensor_data_substitution_dict[self.expand()]
  2186. @data.setter
  2187. def data(self, data):
  2188. deprecate_data()
  2189. with ignore_warnings(SymPyDeprecationWarning):
  2190. _tensor_data_substitution_dict[self] = data
  2191. @data.deleter
  2192. def data(self):
  2193. deprecate_data()
  2194. with ignore_warnings(SymPyDeprecationWarning):
  2195. if self in _tensor_data_substitution_dict:
  2196. del _tensor_data_substitution_dict[self]
  2197. def __iter__(self):
  2198. deprecate_data()
  2199. if not self.data:
  2200. raise ValueError("No iteration on abstract tensors")
  2201. return self.data.flatten().__iter__()
  2202. def _eval_rewrite_as_Indexed(self, *args):
  2203. return Add.fromiter(args)
  2204. def _eval_partial_derivative(self, s):
  2205. # Evaluation like Add
  2206. list_addends = []
  2207. for a in self.args:
  2208. if isinstance(a, TensExpr):
  2209. list_addends.append(a._eval_partial_derivative(s))
  2210. # do not call diff if s is no symbol
  2211. elif s._diff_wrt:
  2212. list_addends.append(a._eval_derivative(s))
  2213. return self.func(*list_addends)
  2214. class Tensor(TensExpr):
  2215. """
  2216. Base tensor class, i.e. this represents a tensor, the single unit to be
  2217. put into an expression.
  2218. Explanation
  2219. ===========
  2220. This object is usually created from a ``TensorHead``, by attaching indices
  2221. to it. Indices preceded by a minus sign are considered contravariant,
  2222. otherwise covariant.
  2223. Examples
  2224. ========
  2225. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead
  2226. >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L")
  2227. >>> mu, nu = tensor_indices('mu nu', Lorentz)
  2228. >>> A = TensorHead("A", [Lorentz, Lorentz])
  2229. >>> A(mu, -nu)
  2230. A(mu, -nu)
  2231. >>> A(mu, -mu)
  2232. A(L_0, -L_0)
  2233. It is also possible to use symbols instead of inidices (appropriate indices
  2234. are then generated automatically).
  2235. >>> from sympy import Symbol
  2236. >>> x = Symbol('x')
  2237. >>> A(x, mu)
  2238. A(x, mu)
  2239. >>> A(x, -x)
  2240. A(L_0, -L_0)
  2241. """
  2242. is_commutative = False
  2243. _index_structure = None # type: _IndexStructure
  2244. args: tTuple[TensorHead, Tuple]
  2245. def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args):
  2246. indices = cls._parse_indices(tensor_head, indices)
  2247. obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args)
  2248. obj._index_structure = _IndexStructure.from_indices(*indices)
  2249. obj._free = obj._index_structure.free[:]
  2250. obj._dum = obj._index_structure.dum[:]
  2251. obj._ext_rank = obj._index_structure._ext_rank
  2252. obj._coeff = S.One
  2253. obj._nocoeff = obj
  2254. obj._component = tensor_head
  2255. obj._components = [tensor_head]
  2256. if tensor_head.rank != len(indices):
  2257. raise ValueError("wrong number of indices")
  2258. obj.is_canon_bp = is_canon_bp
  2259. obj._index_map = Tensor._build_index_map(indices, obj._index_structure)
  2260. return obj
  2261. @property
  2262. def free(self):
  2263. return self._free
  2264. @property
  2265. def dum(self):
  2266. return self._dum
  2267. @property
  2268. def ext_rank(self):
  2269. return self._ext_rank
  2270. @property
  2271. def coeff(self):
  2272. return self._coeff
  2273. @property
  2274. def nocoeff(self):
  2275. return self._nocoeff
  2276. @property
  2277. def component(self):
  2278. return self._component
  2279. @property
  2280. def components(self):
  2281. return self._components
  2282. @property
  2283. def head(self):
  2284. return self.args[0]
  2285. @property
  2286. def indices(self):
  2287. return self.args[1]
  2288. @property
  2289. def free_indices(self):
  2290. return set(self._index_structure.get_free_indices())
  2291. @property
  2292. def index_types(self):
  2293. return self.head.index_types
  2294. @property
  2295. def rank(self):
  2296. return len(self.free_indices)
  2297. @staticmethod
  2298. def _build_index_map(indices, index_structure):
  2299. index_map = {}
  2300. for idx in indices:
  2301. index_map[idx] = (indices.index(idx),)
  2302. return index_map
  2303. def doit(self, **kwargs):
  2304. args, indices, free, dum = TensMul._tensMul_contract_indices([self])
  2305. return args[0]
  2306. @staticmethod
  2307. def _parse_indices(tensor_head, indices):
  2308. if not isinstance(indices, (tuple, list, Tuple)):
  2309. raise TypeError("indices should be an array, got %s" % type(indices))
  2310. indices = list(indices)
  2311. for i, index in enumerate(indices):
  2312. if isinstance(index, Symbol):
  2313. indices[i] = TensorIndex(index, tensor_head.index_types[i], True)
  2314. elif isinstance(index, Mul):
  2315. c, e = index.as_coeff_Mul()
  2316. if c == -1 and isinstance(e, Symbol):
  2317. indices[i] = TensorIndex(e, tensor_head.index_types[i], False)
  2318. else:
  2319. raise ValueError("index not understood: %s" % index)
  2320. elif not isinstance(index, TensorIndex):
  2321. raise TypeError("wrong type for index: %s is %s" % (index, type(index)))
  2322. return indices
  2323. def _set_new_index_structure(self, im, is_canon_bp=False):
  2324. indices = im.get_indices()
  2325. return self._set_indices(*indices, is_canon_bp=is_canon_bp)
  2326. def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
  2327. if len(indices) != self.ext_rank:
  2328. raise ValueError("indices length mismatch")
  2329. return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit()
  2330. def _get_free_indices_set(self):
  2331. return {i[0] for i in self._index_structure.free}
  2332. def _get_dummy_indices_set(self):
  2333. dummy_pos = set(itertools.chain(*self._index_structure.dum))
  2334. return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos}
  2335. def _get_indices_set(self):
  2336. return set(self.args[1].args)
  2337. @property
  2338. def free_in_args(self):
  2339. return [(ind, pos, 0) for ind, pos in self.free]
  2340. @property
  2341. def dum_in_args(self):
  2342. return [(p1, p2, 0, 0) for p1, p2 in self.dum]
  2343. @property
  2344. def free_args(self):
  2345. return sorted([x[0] for x in self.free])
  2346. def commutes_with(self, other):
  2347. """
  2348. :param other:
  2349. :return:
  2350. 0 commute
  2351. 1 anticommute
  2352. None neither commute nor anticommute
  2353. """
  2354. if not isinstance(other, TensExpr):
  2355. return 0
  2356. elif isinstance(other, Tensor):
  2357. return self.component.commutes_with(other.component)
  2358. return NotImplementedError
  2359. def perm2tensor(self, g, is_canon_bp=False):
  2360. """
  2361. Returns the tensor corresponding to the permutation ``g``.
  2362. For further details, see the method in ``TIDS`` with the same name.
  2363. """
  2364. return perm2tensor(self, g, is_canon_bp)
  2365. def canon_bp(self):
  2366. if self.is_canon_bp:
  2367. return self
  2368. expr = self.expand()
  2369. g, dummies, msym = expr._index_structure.indices_canon_args()
  2370. v = components_canon_args([expr.component])
  2371. can = canonicalize(g, dummies, msym, *v)
  2372. if can == 0:
  2373. return S.Zero
  2374. tensor = self.perm2tensor(can, True)
  2375. return tensor
  2376. def split(self):
  2377. return [self]
  2378. def _expand(self, **kwargs):
  2379. return self
  2380. def sorted_components(self):
  2381. return self
  2382. def get_indices(self): # type: () -> List[TensorIndex]
  2383. """
  2384. Get a list of indices, corresponding to those of the tensor.
  2385. """
  2386. return list(self.args[1])
  2387. def get_free_indices(self): # type: () -> List[TensorIndex]
  2388. """
  2389. Get a list of free indices, corresponding to those of the tensor.
  2390. """
  2391. return self._index_structure.get_free_indices()
  2392. def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> Tensor
  2393. # TODO: this could be optimized by only swapping the indices
  2394. # instead of visiting the whole expression tree:
  2395. return self.xreplace(repl)
  2396. def as_base_exp(self):
  2397. return self, S.One
  2398. def substitute_indices(self, *index_tuples):
  2399. """
  2400. Return a tensor with free indices substituted according to ``index_tuples``.
  2401. ``index_types`` list of tuples ``(old_index, new_index)``.
  2402. Examples
  2403. ========
  2404. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
  2405. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  2406. >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
  2407. >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
  2408. >>> t = A(i, k)*B(-k, -j); t
  2409. A(i, L_0)*B(-L_0, -j)
  2410. >>> t.substitute_indices((i, k),(-j, l))
  2411. A(k, L_0)*B(-L_0, l)
  2412. """
  2413. indices = []
  2414. for index in self.indices:
  2415. for ind_old, ind_new in index_tuples:
  2416. if (index.name == ind_old.name and index.tensor_index_type ==
  2417. ind_old.tensor_index_type):
  2418. if index.is_up == ind_old.is_up:
  2419. indices.append(ind_new)
  2420. else:
  2421. indices.append(-ind_new)
  2422. break
  2423. else:
  2424. indices.append(index)
  2425. return self.head(*indices)
  2426. def __call__(self, *indices):
  2427. deprecate_call()
  2428. free_args = self.free_args
  2429. indices = list(indices)
  2430. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  2431. raise ValueError('incompatible types')
  2432. if indices == free_args:
  2433. return self
  2434. t = self.substitute_indices(*list(zip(free_args, indices)))
  2435. # object is rebuilt in order to make sure that all contracted indices
  2436. # get recognized as dummies, but only if there are contracted indices.
  2437. if len({i if i.is_up else -i for i in indices}) != len(indices):
  2438. return t.func(*t.args)
  2439. return t
  2440. # TODO: put this into TensExpr?
  2441. def __iter__(self):
  2442. deprecate_data()
  2443. with ignore_warnings(SymPyDeprecationWarning):
  2444. return self.data.__iter__()
  2445. # TODO: put this into TensExpr?
  2446. def __getitem__(self, item):
  2447. deprecate_data()
  2448. with ignore_warnings(SymPyDeprecationWarning):
  2449. return self.data[item]
  2450. def _extract_data(self, replacement_dict):
  2451. from .array import Array
  2452. for k, v in replacement_dict.items():
  2453. if isinstance(k, Tensor) and k.args[0] == self.args[0]:
  2454. other = k
  2455. array = v
  2456. break
  2457. else:
  2458. raise ValueError("%s not found in %s" % (self, replacement_dict))
  2459. # TODO: inefficient, this should be done at root level only:
  2460. replacement_dict = {k: Array(v) for k, v in replacement_dict.items()}
  2461. array = Array(array)
  2462. dum1 = self.dum
  2463. dum2 = other.dum
  2464. if len(dum2) > 0:
  2465. for pair in dum2:
  2466. # allow `dum2` if the contained values are also in `dum1`.
  2467. if pair not in dum1:
  2468. raise NotImplementedError("%s with contractions is not implemented" % other)
  2469. # Remove elements in `dum2` from `dum1`:
  2470. dum1 = [pair for pair in dum1 if pair not in dum2]
  2471. if len(dum1) > 0:
  2472. indices1 = self.get_indices()
  2473. indices2 = other.get_indices()
  2474. repl = {}
  2475. for p1, p2 in dum1:
  2476. repl[indices2[p2]] = -indices2[p1]
  2477. for pos in (p1, p2):
  2478. if indices1[pos].is_up ^ indices2[pos].is_up:
  2479. metric = replacement_dict[indices1[pos].tensor_index_type]
  2480. if indices1[pos].is_up:
  2481. metric = _TensorDataLazyEvaluator.inverse_matrix(metric)
  2482. array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))
  2483. other = other.xreplace(repl).doit()
  2484. array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))
  2485. free_ind1 = self.get_free_indices()
  2486. free_ind2 = other.get_free_indices()
  2487. return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict)
  2488. @property
  2489. def data(self):
  2490. deprecate_data()
  2491. with ignore_warnings(SymPyDeprecationWarning):
  2492. return _tensor_data_substitution_dict[self]
  2493. @data.setter
  2494. def data(self, data):
  2495. deprecate_data()
  2496. # TODO: check data compatibility with properties of tensor.
  2497. with ignore_warnings(SymPyDeprecationWarning):
  2498. _tensor_data_substitution_dict[self] = data
  2499. @data.deleter
  2500. def data(self):
  2501. deprecate_data()
  2502. with ignore_warnings(SymPyDeprecationWarning):
  2503. if self in _tensor_data_substitution_dict:
  2504. del _tensor_data_substitution_dict[self]
  2505. if self.metric in _tensor_data_substitution_dict:
  2506. del _tensor_data_substitution_dict[self.metric]
  2507. def _print(self):
  2508. indices = [str(ind) for ind in self.indices]
  2509. component = self.component
  2510. if component.rank > 0:
  2511. return ('%s(%s)' % (component.name, ', '.join(indices)))
  2512. else:
  2513. return ('%s' % component.name)
  2514. def equals(self, other):
  2515. if other == 0:
  2516. return self.coeff == 0
  2517. other = _sympify(other)
  2518. if not isinstance(other, TensExpr):
  2519. assert not self.components
  2520. return S.One == other
  2521. def _get_compar_comp(self):
  2522. t = self.canon_bp()
  2523. r = (t.coeff, tuple(t.components), \
  2524. tuple(sorted(t.free)), tuple(sorted(t.dum)))
  2525. return r
  2526. return _get_compar_comp(self) == _get_compar_comp(other)
  2527. def contract_metric(self, g):
  2528. # if metric is not the same, ignore this step:
  2529. if self.component != g:
  2530. return self
  2531. # in case there are free components, do not perform anything:
  2532. if len(self.free) != 0:
  2533. return self
  2534. #antisym = g.index_types[0].metric_antisym
  2535. if g.symmetry == TensorSymmetry.fully_symmetric(-2):
  2536. antisym = 1
  2537. elif g.symmetry == TensorSymmetry.fully_symmetric(2):
  2538. antisym = 0
  2539. elif g.symmetry == TensorSymmetry.no_symmetry(2):
  2540. antisym = None
  2541. else:
  2542. raise NotImplementedError
  2543. sign = S.One
  2544. typ = g.index_types[0]
  2545. if not antisym:
  2546. # g(i, -i)
  2547. sign = sign*typ.dim
  2548. else:
  2549. # g(i, -i)
  2550. sign = sign*typ.dim
  2551. dp0, dp1 = self.dum[0]
  2552. if dp0 < dp1:
  2553. # g(i, -i) = -D with antisymmetric metric
  2554. sign = -sign
  2555. return sign
  2556. def contract_delta(self, metric):
  2557. return self.contract_metric(metric)
  2558. def _eval_rewrite_as_Indexed(self, tens, indices):
  2559. from sympy.tensor.indexed import Indexed
  2560. # TODO: replace .args[0] with .name:
  2561. index_symbols = [i.args[0] for i in self.get_indices()]
  2562. expr = Indexed(tens.args[0], *index_symbols)
  2563. return self._check_add_Sum(expr, index_symbols)
  2564. def _eval_partial_derivative(self, s): # type: (Tensor) -> Expr
  2565. if not isinstance(s, Tensor):
  2566. return S.Zero
  2567. else:
  2568. # @a_i/@a_k = delta_i^k
  2569. # @a_i/@a^k = g_ij delta^j_k
  2570. # @a^i/@a^k = delta^i_k
  2571. # @a^i/@a_k = g^ij delta_j^k
  2572. # TODO: if there is no metric present, the derivative should be zero?
  2573. if self.head != s.head:
  2574. return S.Zero
  2575. # if heads are the same, provide delta and/or metric products
  2576. # for every free index pair in the appropriate tensor
  2577. # assumed that the free indices are in proper order
  2578. # A contravariante index in the derivative becomes covariant
  2579. # after performing the derivative and vice versa
  2580. kronecker_delta_list = [1]
  2581. # not guarantee a correct index order
  2582. for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())):
  2583. if iself.tensor_index_type != iother.tensor_index_type:
  2584. raise ValueError("index types not compatible")
  2585. else:
  2586. tensor_index_type = iself.tensor_index_type
  2587. tensor_metric = tensor_index_type.metric
  2588. dummy = TensorIndex("d_" + str(count), tensor_index_type,
  2589. is_up=iself.is_up)
  2590. if iself.is_up == iother.is_up:
  2591. kroneckerdelta = tensor_index_type.delta(iself, -iother)
  2592. else:
  2593. kroneckerdelta = (
  2594. TensMul(tensor_metric(iself, dummy),
  2595. tensor_index_type.delta(-dummy, -iother))
  2596. )
  2597. kronecker_delta_list.append(kroneckerdelta)
  2598. return TensMul.fromiter(kronecker_delta_list).doit()
  2599. # doit necessary to rename dummy indices accordingly
  2600. class TensMul(TensExpr, AssocOp):
  2601. """
  2602. Product of tensors.
  2603. Parameters
  2604. ==========
  2605. coeff : SymPy coefficient of the tensor
  2606. args
  2607. Attributes
  2608. ==========
  2609. ``components`` : list of ``TensorHead`` of the component tensors
  2610. ``types`` : list of nonrepeated ``TensorIndexType``
  2611. ``free`` : list of ``(ind, ipos, icomp)``, see Notes
  2612. ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes
  2613. ``ext_rank`` : rank of the tensor counting the dummy indices
  2614. ``rank`` : rank of the tensor
  2615. ``coeff`` : SymPy coefficient of the tensor
  2616. ``free_args`` : list of the free indices in sorted order
  2617. ``is_canon_bp`` : ``True`` if the tensor in in canonical form
  2618. Notes
  2619. =====
  2620. ``args[0]`` list of ``TensorHead`` of the component tensors.
  2621. ``args[1]`` list of ``(ind, ipos, icomp)``
  2622. where ``ind`` is a free index, ``ipos`` is the slot position
  2623. of ``ind`` in the ``icomp``-th component tensor.
  2624. ``args[2]`` list of tuples representing dummy indices.
  2625. ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant
  2626. dummy index is the ``ipos1``-th slot position in the ``icomp1``-th
  2627. component tensor; the corresponding covariant index is
  2628. in the ``ipos2`` slot position in the ``icomp2``-th component tensor.
  2629. """
  2630. identity = S.One
  2631. _index_structure = None # type: _IndexStructure
  2632. def __new__(cls, *args, **kw_args):
  2633. is_canon_bp = kw_args.get('is_canon_bp', False)
  2634. args = list(map(_sympify, args))
  2635. # Flatten:
  2636. args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])]
  2637. args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False)
  2638. # Data for indices:
  2639. index_types = [i.tensor_index_type for i in indices]
  2640. index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
  2641. obj = TensExpr.__new__(cls, *args)
  2642. obj._indices = indices
  2643. obj._index_types = index_types[:]
  2644. obj._index_structure = index_structure
  2645. obj._free = index_structure.free[:]
  2646. obj._dum = index_structure.dum[:]
  2647. obj._free_indices = {x[0] for x in obj.free}
  2648. obj._rank = len(obj.free)
  2649. obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
  2650. obj._coeff = S.One
  2651. obj._is_canon_bp = is_canon_bp
  2652. return obj
  2653. index_types = property(lambda self: self._index_types)
  2654. free = property(lambda self: self._free)
  2655. dum = property(lambda self: self._dum)
  2656. free_indices = property(lambda self: self._free_indices)
  2657. rank = property(lambda self: self._rank)
  2658. ext_rank = property(lambda self: self._ext_rank)
  2659. @staticmethod
  2660. def _indices_to_free_dum(args_indices):
  2661. free2pos1 = {}
  2662. free2pos2 = {}
  2663. dummy_data = []
  2664. indices = []
  2665. # Notation for positions (to better understand the code):
  2666. # `pos1`: position in the `args`.
  2667. # `pos2`: position in the indices.
  2668. # Example:
  2669. # A(i, j)*B(k, m, n)*C(p)
  2670. # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul).
  2671. # `pos2` of `n` is 4 because it's the fifth overall index.
  2672. # Counter for the index position wrt the whole expression:
  2673. pos2 = 0
  2674. for pos1, arg_indices in enumerate(args_indices):
  2675. for index_pos, index in enumerate(arg_indices):
  2676. if not isinstance(index, TensorIndex):
  2677. raise TypeError("expected TensorIndex")
  2678. if -index in free2pos1:
  2679. # Dummy index detected:
  2680. other_pos1 = free2pos1.pop(-index)
  2681. other_pos2 = free2pos2.pop(-index)
  2682. if index.is_up:
  2683. dummy_data.append((index, pos1, other_pos1, pos2, other_pos2))
  2684. else:
  2685. dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2))
  2686. indices.append(index)
  2687. elif index in free2pos1:
  2688. raise ValueError("Repeated index: %s" % index)
  2689. else:
  2690. free2pos1[index] = pos1
  2691. free2pos2[index] = pos2
  2692. indices.append(index)
  2693. pos2 += 1
  2694. free = [(i, p) for (i, p) in free2pos2.items()]
  2695. free_names = [i.name for i in free2pos2.keys()]
  2696. dummy_data.sort(key=lambda x: x[3])
  2697. return indices, free, free_names, dummy_data
  2698. @staticmethod
  2699. def _dummy_data_to_dum(dummy_data):
  2700. return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data]
  2701. @staticmethod
  2702. def _tensMul_contract_indices(args, replace_indices=True):
  2703. replacements = [{} for _ in args]
  2704. #_index_order = all(_has_index_order(arg) for arg in args)
  2705. args_indices = [get_indices(arg) for arg in args]
  2706. indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
  2707. cdt = defaultdict(int)
  2708. def dummy_name_gen(tensor_index_type):
  2709. nd = str(cdt[tensor_index_type])
  2710. cdt[tensor_index_type] += 1
  2711. return tensor_index_type.dummy_name + '_' + nd
  2712. if replace_indices:
  2713. for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data:
  2714. index_type = old_index.tensor_index_type
  2715. while True:
  2716. dummy_name = dummy_name_gen(index_type)
  2717. if dummy_name not in free_names:
  2718. break
  2719. dummy = TensorIndex(dummy_name, index_type, True)
  2720. replacements[pos1cov][old_index] = dummy
  2721. replacements[pos1contra][-old_index] = -dummy
  2722. indices[pos2cov] = dummy
  2723. indices[pos2contra] = -dummy
  2724. args = [
  2725. arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg
  2726. for arg, repl in zip(args, replacements)]
  2727. dum = TensMul._dummy_data_to_dum(dummy_data)
  2728. return args, indices, free, dum
  2729. @staticmethod
  2730. def _get_components_from_args(args):
  2731. """
  2732. Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied
  2733. by one another.
  2734. """
  2735. components = []
  2736. for arg in args:
  2737. if not isinstance(arg, TensExpr):
  2738. continue
  2739. if isinstance(arg, TensAdd):
  2740. continue
  2741. components.extend(arg.components)
  2742. return components
  2743. @staticmethod
  2744. def _rebuild_tensors_list(args, index_structure):
  2745. indices = index_structure.get_indices()
  2746. #tensors = [None for i in components] # pre-allocate list
  2747. ind_pos = 0
  2748. for i, arg in enumerate(args):
  2749. if not isinstance(arg, TensExpr):
  2750. continue
  2751. prev_pos = ind_pos
  2752. ind_pos += arg.ext_rank
  2753. args[i] = Tensor(arg.component, indices[prev_pos:ind_pos])
  2754. def doit(self, **kwargs):
  2755. is_canon_bp = self._is_canon_bp
  2756. deep = kwargs.get('deep', True)
  2757. if deep:
  2758. args = [arg.doit(**kwargs) for arg in self.args]
  2759. else:
  2760. args = self.args
  2761. args = [arg for arg in args if arg != self.identity]
  2762. # Extract non-tensor coefficients:
  2763. coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One)
  2764. args = [arg for arg in args if isinstance(arg, TensExpr)]
  2765. if len(args) == 0:
  2766. return coeff
  2767. if coeff != self.identity:
  2768. args = [coeff] + args
  2769. if coeff == 0:
  2770. return S.Zero
  2771. if len(args) == 1:
  2772. return args[0]
  2773. args, indices, free, dum = TensMul._tensMul_contract_indices(args)
  2774. # Data for indices:
  2775. index_types = [i.tensor_index_type for i in indices]
  2776. index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp)
  2777. obj = self.func(*args)
  2778. obj._index_types = index_types
  2779. obj._index_structure = index_structure
  2780. obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum)
  2781. obj._coeff = coeff
  2782. obj._is_canon_bp = is_canon_bp
  2783. return obj
  2784. # TODO: this method should be private
  2785. # TODO: should this method be renamed _from_components_free_dum ?
  2786. @staticmethod
  2787. def from_data(coeff, components, free, dum, **kw_args):
  2788. return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit()
  2789. @staticmethod
  2790. def _get_tensors_from_components_free_dum(components, free, dum):
  2791. """
  2792. Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``.
  2793. """
  2794. index_structure = _IndexStructure.from_components_free_dum(components, free, dum)
  2795. indices = index_structure.get_indices()
  2796. tensors = [None for i in components] # pre-allocate list
  2797. # distribute indices on components to build a list of tensors:
  2798. ind_pos = 0
  2799. for i, component in enumerate(components):
  2800. prev_pos = ind_pos
  2801. ind_pos += component.rank
  2802. tensors[i] = Tensor(component, indices[prev_pos:ind_pos])
  2803. return tensors
  2804. def _get_free_indices_set(self):
  2805. return {i[0] for i in self.free}
  2806. def _get_dummy_indices_set(self):
  2807. dummy_pos = set(itertools.chain(*self.dum))
  2808. return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos}
  2809. def _get_position_offset_for_indices(self):
  2810. arg_offset = [None for i in range(self.ext_rank)]
  2811. counter = 0
  2812. for i, arg in enumerate(self.args):
  2813. if not isinstance(arg, TensExpr):
  2814. continue
  2815. for j in range(arg.ext_rank):
  2816. arg_offset[j + counter] = counter
  2817. counter += arg.ext_rank
  2818. return arg_offset
  2819. @property
  2820. def free_args(self):
  2821. return sorted([x[0] for x in self.free])
  2822. @property
  2823. def components(self):
  2824. return self._get_components_from_args(self.args)
  2825. @property
  2826. def free_in_args(self):
  2827. arg_offset = self._get_position_offset_for_indices()
  2828. argpos = self._get_indices_to_args_pos()
  2829. return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free]
  2830. @property
  2831. def coeff(self):
  2832. # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)])
  2833. return self._coeff
  2834. @property
  2835. def nocoeff(self):
  2836. return self.func(*[t for t in self.args if isinstance(t, TensExpr)]).doit()
  2837. @property
  2838. def dum_in_args(self):
  2839. arg_offset = self._get_position_offset_for_indices()
  2840. argpos = self._get_indices_to_args_pos()
  2841. return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum]
  2842. def equals(self, other):
  2843. if other == 0:
  2844. return self.coeff == 0
  2845. other = _sympify(other)
  2846. if not isinstance(other, TensExpr):
  2847. assert not self.components
  2848. return self.coeff == other
  2849. return self.canon_bp() == other.canon_bp()
  2850. def get_indices(self):
  2851. """
  2852. Returns the list of indices of the tensor.
  2853. Explanation
  2854. ===========
  2855. The indices are listed in the order in which they appear in the
  2856. component tensors.
  2857. The dummy indices are given a name which does not collide with
  2858. the names of the free indices.
  2859. Examples
  2860. ========
  2861. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  2862. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  2863. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  2864. >>> g = Lorentz.metric
  2865. >>> p, q = tensor_heads('p,q', [Lorentz])
  2866. >>> t = p(m1)*g(m0,m2)
  2867. >>> t.get_indices()
  2868. [m1, m0, m2]
  2869. >>> t2 = p(m1)*g(-m1, m2)
  2870. >>> t2.get_indices()
  2871. [L_0, -L_0, m2]
  2872. """
  2873. return self._indices
  2874. def get_free_indices(self): # type: () -> List[TensorIndex]
  2875. """
  2876. Returns the list of free indices of the tensor.
  2877. Explanation
  2878. ===========
  2879. The indices are listed in the order in which they appear in the
  2880. component tensors.
  2881. Examples
  2882. ========
  2883. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  2884. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  2885. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  2886. >>> g = Lorentz.metric
  2887. >>> p, q = tensor_heads('p,q', [Lorentz])
  2888. >>> t = p(m1)*g(m0,m2)
  2889. >>> t.get_free_indices()
  2890. [m1, m0, m2]
  2891. >>> t2 = p(m1)*g(-m1, m2)
  2892. >>> t2.get_free_indices()
  2893. [m2]
  2894. """
  2895. return self._index_structure.get_free_indices()
  2896. def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr
  2897. return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args])
  2898. def split(self):
  2899. """
  2900. Returns a list of tensors, whose product is ``self``.
  2901. Explanation
  2902. ===========
  2903. Dummy indices contracted among different tensor components
  2904. become free indices with the same name as the one used to
  2905. represent the dummy indices.
  2906. Examples
  2907. ========
  2908. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry
  2909. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  2910. >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
  2911. >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
  2912. >>> t = A(a,b)*B(-b,c)
  2913. >>> t
  2914. A(a, L_0)*B(-L_0, c)
  2915. >>> t.split()
  2916. [A(a, L_0), B(-L_0, c)]
  2917. """
  2918. if self.args == ():
  2919. return [self]
  2920. splitp = []
  2921. res = 1
  2922. for arg in self.args:
  2923. if isinstance(arg, Tensor):
  2924. splitp.append(res*arg)
  2925. res = 1
  2926. else:
  2927. res *= arg
  2928. return splitp
  2929. def _expand(self, **hints):
  2930. # TODO: temporary solution, in the future this should be linked to
  2931. # `Expr.expand`.
  2932. args = [_expand(arg, **hints) for arg in self.args]
  2933. args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in args]
  2934. return TensAdd(*[
  2935. TensMul(*i) for i in itertools.product(*args1)]
  2936. )
  2937. def __neg__(self):
  2938. return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit()
  2939. def __getitem__(self, item):
  2940. deprecate_data()
  2941. with ignore_warnings(SymPyDeprecationWarning):
  2942. return self.data[item]
  2943. def _get_args_for_traditional_printer(self):
  2944. args = list(self.args)
  2945. if (self.coeff < 0) == True:
  2946. # expressions like "-A(a)"
  2947. sign = "-"
  2948. if self.coeff == S.NegativeOne:
  2949. args = args[1:]
  2950. else:
  2951. args[0] = -args[0]
  2952. else:
  2953. sign = ""
  2954. return sign, args
  2955. def _sort_args_for_sorted_components(self):
  2956. """
  2957. Returns the ``args`` sorted according to the components commutation
  2958. properties.
  2959. Explanation
  2960. ===========
  2961. The sorting is done taking into account the commutation group
  2962. of the component tensors.
  2963. """
  2964. cv = [arg for arg in self.args if isinstance(arg, TensExpr)]
  2965. sign = 1
  2966. n = len(cv) - 1
  2967. for i in range(n):
  2968. for j in range(n, i, -1):
  2969. c = cv[j-1].commutes_with(cv[j])
  2970. # if `c` is `None`, it does neither commute nor anticommute, skip:
  2971. if c not in (0, 1):
  2972. continue
  2973. typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name)
  2974. typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name)
  2975. if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name):
  2976. cv[j-1], cv[j] = cv[j], cv[j-1]
  2977. # if `c` is 1, the anticommute, so change sign:
  2978. if c:
  2979. sign = -sign
  2980. coeff = sign * self.coeff
  2981. if coeff != 1:
  2982. return [coeff] + cv
  2983. return cv
  2984. def sorted_components(self):
  2985. """
  2986. Returns a tensor product with sorted components.
  2987. """
  2988. return TensMul(*self._sort_args_for_sorted_components()).doit()
  2989. def perm2tensor(self, g, is_canon_bp=False):
  2990. """
  2991. Returns the tensor corresponding to the permutation ``g``
  2992. For further details, see the method in ``TIDS`` with the same name.
  2993. """
  2994. return perm2tensor(self, g, is_canon_bp=is_canon_bp)
  2995. def canon_bp(self):
  2996. """
  2997. Canonicalize using the Butler-Portugal algorithm for canonicalization
  2998. under monoterm symmetries.
  2999. Examples
  3000. ========
  3001. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry
  3002. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3003. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3004. >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
  3005. >>> t = A(m0,-m1)*A(m1,-m0)
  3006. >>> t.canon_bp()
  3007. -A(L_0, L_1)*A(-L_0, -L_1)
  3008. >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0)
  3009. >>> t.canon_bp()
  3010. 0
  3011. """
  3012. if self._is_canon_bp:
  3013. return self
  3014. expr = self.expand()
  3015. if isinstance(expr, TensAdd):
  3016. return expr.canon_bp()
  3017. if not expr.components:
  3018. return expr
  3019. t = expr.sorted_components()
  3020. g, dummies, msym = t._index_structure.indices_canon_args()
  3021. v = components_canon_args(t.components)
  3022. can = canonicalize(g, dummies, msym, *v)
  3023. if can == 0:
  3024. return S.Zero
  3025. tmul = t.perm2tensor(can, True)
  3026. return tmul
  3027. def contract_delta(self, delta):
  3028. t = self.contract_metric(delta)
  3029. return t
  3030. def _get_indices_to_args_pos(self):
  3031. """
  3032. Get a dict mapping the index position to TensMul's argument number.
  3033. """
  3034. pos_map = dict()
  3035. pos_counter = 0
  3036. for arg_i, arg in enumerate(self.args):
  3037. if not isinstance(arg, TensExpr):
  3038. continue
  3039. assert isinstance(arg, Tensor)
  3040. for i in range(arg.ext_rank):
  3041. pos_map[pos_counter] = arg_i
  3042. pos_counter += 1
  3043. return pos_map
  3044. def contract_metric(self, g):
  3045. """
  3046. Raise or lower indices with the metric ``g``.
  3047. Parameters
  3048. ==========
  3049. g : metric
  3050. Notes
  3051. =====
  3052. See the ``TensorIndexType`` docstring for the contraction conventions.
  3053. Examples
  3054. ========
  3055. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads
  3056. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3057. >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz)
  3058. >>> g = Lorentz.metric
  3059. >>> p, q = tensor_heads('p,q', [Lorentz])
  3060. >>> t = p(m0)*q(m1)*g(-m0, -m1)
  3061. >>> t.canon_bp()
  3062. metric(L_0, L_1)*p(-L_0)*q(-L_1)
  3063. >>> t.contract_metric(g).canon_bp()
  3064. p(L_0)*q(-L_0)
  3065. """
  3066. expr = self.expand()
  3067. if self != expr:
  3068. expr = expr.canon_bp()
  3069. return expr.contract_metric(g)
  3070. pos_map = self._get_indices_to_args_pos()
  3071. args = list(self.args)
  3072. #antisym = g.index_types[0].metric_antisym
  3073. if g.symmetry == TensorSymmetry.fully_symmetric(-2):
  3074. antisym = 1
  3075. elif g.symmetry == TensorSymmetry.fully_symmetric(2):
  3076. antisym = 0
  3077. elif g.symmetry == TensorSymmetry.no_symmetry(2):
  3078. antisym = None
  3079. else:
  3080. raise NotImplementedError
  3081. # list of positions of the metric ``g`` inside ``args``
  3082. gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g]
  3083. if not gpos:
  3084. return self
  3085. # Sign is either 1 or -1, to correct the sign after metric contraction
  3086. # (for spinor indices).
  3087. sign = 1
  3088. dum = self.dum[:]
  3089. free = self.free[:]
  3090. elim = set()
  3091. for gposx in gpos:
  3092. if gposx in elim:
  3093. continue
  3094. free1 = [x for x in free if pos_map[x[1]] == gposx]
  3095. dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx]
  3096. if not dum1:
  3097. continue
  3098. elim.add(gposx)
  3099. # subs with the multiplication neutral element, that is, remove it:
  3100. args[gposx] = 1
  3101. if len(dum1) == 2:
  3102. if not antisym:
  3103. dum10, dum11 = dum1
  3104. if pos_map[dum10[1]] == gposx:
  3105. # the index with pos p0 contravariant
  3106. p0 = dum10[0]
  3107. else:
  3108. # the index with pos p0 is covariant
  3109. p0 = dum10[1]
  3110. if pos_map[dum11[1]] == gposx:
  3111. # the index with pos p1 is contravariant
  3112. p1 = dum11[0]
  3113. else:
  3114. # the index with pos p1 is covariant
  3115. p1 = dum11[1]
  3116. dum.append((p0, p1))
  3117. else:
  3118. dum10, dum11 = dum1
  3119. # change the sign to bring the indices of the metric to contravariant
  3120. # form; change the sign if dum10 has the metric index in position 0
  3121. if pos_map[dum10[1]] == gposx:
  3122. # the index with pos p0 is contravariant
  3123. p0 = dum10[0]
  3124. if dum10[1] == 1:
  3125. sign = -sign
  3126. else:
  3127. # the index with pos p0 is covariant
  3128. p0 = dum10[1]
  3129. if dum10[0] == 0:
  3130. sign = -sign
  3131. if pos_map[dum11[1]] == gposx:
  3132. # the index with pos p1 is contravariant
  3133. p1 = dum11[0]
  3134. sign = -sign
  3135. else:
  3136. # the index with pos p1 is covariant
  3137. p1 = dum11[1]
  3138. dum.append((p0, p1))
  3139. elif len(dum1) == 1:
  3140. if not antisym:
  3141. dp0, dp1 = dum1[0]
  3142. if pos_map[dp0] == pos_map[dp1]:
  3143. # g(i, -i)
  3144. typ = g.index_types[0]
  3145. sign = sign*typ.dim
  3146. else:
  3147. # g(i0, i1)*p(-i1)
  3148. if pos_map[dp0] == gposx:
  3149. p1 = dp1
  3150. else:
  3151. p1 = dp0
  3152. ind, p = free1[0]
  3153. free.append((ind, p1))
  3154. else:
  3155. dp0, dp1 = dum1[0]
  3156. if pos_map[dp0] == pos_map[dp1]:
  3157. # g(i, -i)
  3158. typ = g.index_types[0]
  3159. sign = sign*typ.dim
  3160. if dp0 < dp1:
  3161. # g(i, -i) = -D with antisymmetric metric
  3162. sign = -sign
  3163. else:
  3164. # g(i0, i1)*p(-i1)
  3165. if pos_map[dp0] == gposx:
  3166. p1 = dp1
  3167. if dp0 == 0:
  3168. sign = -sign
  3169. else:
  3170. p1 = dp0
  3171. ind, p = free1[0]
  3172. free.append((ind, p1))
  3173. dum = [x for x in dum if x not in dum1]
  3174. free = [x for x in free if x not in free1]
  3175. # shift positions:
  3176. shift = 0
  3177. shifts = [0]*len(args)
  3178. for i in range(len(args)):
  3179. if i in elim:
  3180. shift += 2
  3181. continue
  3182. shifts[i] = shift
  3183. free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim]
  3184. dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for i, (p0, p1) in enumerate(dum) if pos_map[p0] not in elim and pos_map[p1] not in elim]
  3185. res = sign*TensMul(*args).doit()
  3186. if not isinstance(res, TensExpr):
  3187. return res
  3188. im = _IndexStructure.from_components_free_dum(res.components, free, dum)
  3189. return res._set_new_index_structure(im)
  3190. def _set_new_index_structure(self, im, is_canon_bp=False):
  3191. indices = im.get_indices()
  3192. return self._set_indices(*indices, is_canon_bp=is_canon_bp)
  3193. def _set_indices(self, *indices, is_canon_bp=False, **kw_args):
  3194. if len(indices) != self.ext_rank:
  3195. raise ValueError("indices length mismatch")
  3196. args = list(self.args)[:]
  3197. pos = 0
  3198. for i, arg in enumerate(args):
  3199. if not isinstance(arg, TensExpr):
  3200. continue
  3201. assert isinstance(arg, Tensor)
  3202. ext_rank = arg.ext_rank
  3203. args[i] = arg._set_indices(*indices[pos:pos+ext_rank])
  3204. pos += ext_rank
  3205. return TensMul(*args, is_canon_bp=is_canon_bp).doit()
  3206. @staticmethod
  3207. def _index_replacement_for_contract_metric(args, free, dum):
  3208. for arg in args:
  3209. if not isinstance(arg, TensExpr):
  3210. continue
  3211. assert isinstance(arg, Tensor)
  3212. def substitute_indices(self, *index_tuples):
  3213. new_args = []
  3214. for arg in self.args:
  3215. if isinstance(arg, TensExpr):
  3216. arg = arg.substitute_indices(*index_tuples)
  3217. new_args.append(arg)
  3218. return TensMul(*new_args).doit()
  3219. def __call__(self, *indices):
  3220. deprecate_call()
  3221. free_args = self.free_args
  3222. indices = list(indices)
  3223. if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]:
  3224. raise ValueError('incompatible types')
  3225. if indices == free_args:
  3226. return self
  3227. t = self.substitute_indices(*list(zip(free_args, indices)))
  3228. # object is rebuilt in order to make sure that all contracted indices
  3229. # get recognized as dummies, but only if there are contracted indices.
  3230. if len({i if i.is_up else -i for i in indices}) != len(indices):
  3231. return t.func(*t.args)
  3232. return t
  3233. def _extract_data(self, replacement_dict):
  3234. args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)])
  3235. coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One)
  3236. indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices)
  3237. dum = TensMul._dummy_data_to_dum(dummy_data)
  3238. ext_rank = self.ext_rank
  3239. free.sort(key=lambda x: x[1])
  3240. free_indices = [i[0] for i in free]
  3241. return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank)
  3242. @property
  3243. def data(self):
  3244. deprecate_data()
  3245. with ignore_warnings(SymPyDeprecationWarning):
  3246. dat = _tensor_data_substitution_dict[self.expand()]
  3247. return dat
  3248. @data.setter
  3249. def data(self, data):
  3250. deprecate_data()
  3251. raise ValueError("Not possible to set component data to a tensor expression")
  3252. @data.deleter
  3253. def data(self):
  3254. deprecate_data()
  3255. raise ValueError("Not possible to delete component data to a tensor expression")
  3256. def __iter__(self):
  3257. deprecate_data()
  3258. with ignore_warnings(SymPyDeprecationWarning):
  3259. if self.data is None:
  3260. raise ValueError("No iteration on abstract tensors")
  3261. return self.data.__iter__()
  3262. def _eval_rewrite_as_Indexed(self, *args):
  3263. from sympy.concrete.summations import Sum
  3264. index_symbols = [i.args[0] for i in self.get_indices()]
  3265. args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args]
  3266. expr = Mul.fromiter(args)
  3267. return self._check_add_Sum(expr, index_symbols)
  3268. def _eval_partial_derivative(self, s):
  3269. # Evaluation like Mul
  3270. terms = []
  3271. for i, arg in enumerate(self.args):
  3272. # checking whether some tensor instance is differentiated
  3273. # or some other thing is necessary, but ugly
  3274. if isinstance(arg, TensExpr):
  3275. d = arg._eval_partial_derivative(s)
  3276. else:
  3277. # do not call diff is s is no symbol
  3278. if s._diff_wrt:
  3279. d = arg._eval_derivative(s)
  3280. else:
  3281. d = S.Zero
  3282. if d:
  3283. terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:]))
  3284. return TensAdd.fromiter(terms)
  3285. class TensorElement(TensExpr):
  3286. """
  3287. Tensor with evaluated components.
  3288. Examples
  3289. ========
  3290. >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry
  3291. >>> from sympy import symbols
  3292. >>> L = TensorIndexType("L")
  3293. >>> i, j, k = symbols("i j k")
  3294. >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2))
  3295. >>> A(i, j).get_free_indices()
  3296. [i, j]
  3297. If we want to set component ``i`` to a specific value, use the
  3298. ``TensorElement`` class:
  3299. >>> from sympy.tensor.tensor import TensorElement
  3300. >>> te = TensorElement(A(i, j), {i: 2})
  3301. As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd
  3302. element), the free indices will only contain ``j``:
  3303. >>> te.get_free_indices()
  3304. [j]
  3305. """
  3306. def __new__(cls, expr, index_map):
  3307. if not isinstance(expr, Tensor):
  3308. # remap
  3309. if not isinstance(expr, TensExpr):
  3310. raise TypeError("%s is not a tensor expression" % expr)
  3311. return expr.func(*[TensorElement(arg, index_map) for arg in expr.args])
  3312. expr_free_indices = expr.get_free_indices()
  3313. name_translation = {i.args[0]: i for i in expr_free_indices}
  3314. index_map = {name_translation.get(index, index): value for index, value in index_map.items()}
  3315. index_map = {index: value for index, value in index_map.items() if index in expr_free_indices}
  3316. if len(index_map) == 0:
  3317. return expr
  3318. free_indices = [i for i in expr_free_indices if i not in index_map.keys()]
  3319. index_map = Dict(index_map)
  3320. obj = TensExpr.__new__(cls, expr, index_map)
  3321. obj._free_indices = free_indices
  3322. return obj
  3323. @property
  3324. def free(self):
  3325. return [(index, i) for i, index in enumerate(self.get_free_indices())]
  3326. @property
  3327. def dum(self):
  3328. # TODO: inherit dummies from expr
  3329. return []
  3330. @property
  3331. def expr(self):
  3332. return self._args[0]
  3333. @property
  3334. def index_map(self):
  3335. return self._args[1]
  3336. @property
  3337. def coeff(self):
  3338. return S.One
  3339. @property
  3340. def nocoeff(self):
  3341. return self
  3342. def get_free_indices(self):
  3343. return self._free_indices
  3344. def _replace_indices(self, repl): # type: (tDict[TensorIndex, TensorIndex]) -> TensExpr
  3345. # TODO: can be improved:
  3346. return self.xreplace(repl)
  3347. def get_indices(self):
  3348. return self.get_free_indices()
  3349. def _extract_data(self, replacement_dict):
  3350. ret_indices, array = self.expr._extract_data(replacement_dict)
  3351. index_map = self.index_map
  3352. slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices)
  3353. ret_indices = [i for i in ret_indices if i not in index_map]
  3354. array = array.__getitem__(slice_tuple)
  3355. return ret_indices, array
  3356. def canon_bp(p):
  3357. """
  3358. Butler-Portugal canonicalization. See ``tensor_can.py`` from the
  3359. combinatorics module for the details.
  3360. """
  3361. if isinstance(p, TensExpr):
  3362. return p.canon_bp()
  3363. return p
  3364. def tensor_mul(*a):
  3365. """
  3366. product of tensors
  3367. """
  3368. if not a:
  3369. return TensMul.from_data(S.One, [], [], [])
  3370. t = a[0]
  3371. for tx in a[1:]:
  3372. t = t*tx
  3373. return t
  3374. def riemann_cyclic_replace(t_r):
  3375. """
  3376. replace Riemann tensor with an equivalent expression
  3377. ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)``
  3378. """
  3379. free = sorted(t_r.free, key=lambda x: x[1])
  3380. m, n, p, q = [x[0] for x in free]
  3381. t0 = t_r*Rational(2, 3)
  3382. t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3)
  3383. t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3)
  3384. t3 = t0 + t1 + t2
  3385. return t3
  3386. def riemann_cyclic(t2):
  3387. """
  3388. Replace each Riemann tensor with an equivalent expression
  3389. satisfying the cyclic identity.
  3390. This trick is discussed in the reference guide to Cadabra.
  3391. Examples
  3392. ========
  3393. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry
  3394. >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L')
  3395. >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz)
  3396. >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
  3397. >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
  3398. >>> riemann_cyclic(t)
  3399. 0
  3400. """
  3401. t2 = t2.expand()
  3402. if isinstance(t2, (TensMul, Tensor)):
  3403. args = [t2]
  3404. else:
  3405. args = t2.args
  3406. a1 = [x.split() for x in args]
  3407. a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1]
  3408. a3 = [tensor_mul(*v) for v in a2]
  3409. t3 = TensAdd(*a3).doit()
  3410. if not t3:
  3411. return t3
  3412. else:
  3413. return canon_bp(t3)
  3414. def get_lines(ex, index_type):
  3415. """
  3416. Returns ``(lines, traces, rest)`` for an index type,
  3417. where ``lines`` is the list of list of positions of a matrix line,
  3418. ``traces`` is the list of list of traced matrix lines,
  3419. ``rest`` is the rest of the elements ot the tensor.
  3420. """
  3421. def _join_lines(a):
  3422. i = 0
  3423. while i < len(a):
  3424. x = a[i]
  3425. xend = x[-1]
  3426. xstart = x[0]
  3427. hit = True
  3428. while hit:
  3429. hit = False
  3430. for j in range(i + 1, len(a)):
  3431. if j >= len(a):
  3432. break
  3433. if a[j][0] == xend:
  3434. hit = True
  3435. x.extend(a[j][1:])
  3436. xend = x[-1]
  3437. a.pop(j)
  3438. continue
  3439. if a[j][0] == xstart:
  3440. hit = True
  3441. a[i] = reversed(a[j][1:]) + x
  3442. x = a[i]
  3443. xstart = a[i][0]
  3444. a.pop(j)
  3445. continue
  3446. if a[j][-1] == xend:
  3447. hit = True
  3448. x.extend(reversed(a[j][:-1]))
  3449. xend = x[-1]
  3450. a.pop(j)
  3451. continue
  3452. if a[j][-1] == xstart:
  3453. hit = True
  3454. a[i] = a[j][:-1] + x
  3455. x = a[i]
  3456. xstart = x[0]
  3457. a.pop(j)
  3458. continue
  3459. i += 1
  3460. return a
  3461. arguments = ex.args
  3462. dt = {}
  3463. for c in ex.args:
  3464. if not isinstance(c, TensExpr):
  3465. continue
  3466. if c in dt:
  3467. continue
  3468. index_types = c.index_types
  3469. a = []
  3470. for i in range(len(index_types)):
  3471. if index_types[i] is index_type:
  3472. a.append(i)
  3473. if len(a) > 2:
  3474. raise ValueError('at most two indices of type %s allowed' % index_type)
  3475. if len(a) == 2:
  3476. dt[c] = a
  3477. #dum = ex.dum
  3478. lines = []
  3479. traces = []
  3480. traces1 = []
  3481. #indices_to_args_pos = ex._get_indices_to_args_pos()
  3482. # TODO: add a dum_to_components_map ?
  3483. for p0, p1, c0, c1 in ex.dum_in_args:
  3484. if arguments[c0] not in dt:
  3485. continue
  3486. if c0 == c1:
  3487. traces.append([c0])
  3488. continue
  3489. ta0 = dt[arguments[c0]]
  3490. ta1 = dt[arguments[c1]]
  3491. if p0 not in ta0:
  3492. continue
  3493. if ta0.index(p0) == ta1.index(p1):
  3494. # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1;
  3495. # to deal with this case one could add to the position
  3496. # a flag for transposition;
  3497. # one could write [(c0, False), (c1, True)]
  3498. raise NotImplementedError
  3499. # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1
  3500. # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0
  3501. ta0 = dt[arguments[c0]]
  3502. b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0)
  3503. lines1 = lines[:]
  3504. for line in lines:
  3505. if line[-1] == b0:
  3506. if line[0] == b1:
  3507. n = line.index(min(line))
  3508. traces1.append(line)
  3509. traces.append(line[n:] + line[:n])
  3510. else:
  3511. line.append(b1)
  3512. break
  3513. elif line[0] == b1:
  3514. line.insert(0, b0)
  3515. break
  3516. else:
  3517. lines1.append([b0, b1])
  3518. lines = [x for x in lines1 if x not in traces1]
  3519. lines = _join_lines(lines)
  3520. rest = []
  3521. for line in lines:
  3522. for y in line:
  3523. rest.append(y)
  3524. for line in traces:
  3525. for y in line:
  3526. rest.append(y)
  3527. rest = [x for x in range(len(arguments)) if x not in rest]
  3528. return lines, traces, rest
  3529. def get_free_indices(t):
  3530. if not isinstance(t, TensExpr):
  3531. return ()
  3532. return t.get_free_indices()
  3533. def get_indices(t):
  3534. if not isinstance(t, TensExpr):
  3535. return ()
  3536. return t.get_indices()
  3537. def get_index_structure(t):
  3538. if isinstance(t, TensExpr):
  3539. return t._index_structure
  3540. return _IndexStructure([], [], [], [])
  3541. def get_coeff(t):
  3542. if isinstance(t, Tensor):
  3543. return S.One
  3544. if isinstance(t, TensMul):
  3545. return t.coeff
  3546. if isinstance(t, TensExpr):
  3547. raise ValueError("no coefficient associated to this tensor expression")
  3548. return t
  3549. def contract_metric(t, g):
  3550. if isinstance(t, TensExpr):
  3551. return t.contract_metric(g)
  3552. return t
  3553. def perm2tensor(t, g, is_canon_bp=False):
  3554. """
  3555. Returns the tensor corresponding to the permutation ``g``
  3556. For further details, see the method in ``TIDS`` with the same name.
  3557. """
  3558. if not isinstance(t, TensExpr):
  3559. return t
  3560. elif isinstance(t, (Tensor, TensMul)):
  3561. nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp)
  3562. res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp)
  3563. if g[-1] != len(g) - 1:
  3564. return -res
  3565. return res
  3566. raise NotImplementedError()
  3567. def substitute_indices(t, *index_tuples):
  3568. if not isinstance(t, TensExpr):
  3569. return t
  3570. return t.substitute_indices(*index_tuples)
  3571. def _expand(expr, **kwargs):
  3572. if isinstance(expr, TensExpr):
  3573. return expr._expand(**kwargs)
  3574. else:
  3575. return expr.expand(**kwargs)