m2m模型翻译
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.

1918 lines
73 KiB

6 months ago
  1. import collections.abc
  2. import operator
  3. from collections import defaultdict, Counter
  4. from functools import reduce
  5. import itertools
  6. from itertools import accumulate
  7. from typing import Optional, List, Dict as tDict, Tuple as tTuple
  8. import typing
  9. from sympy.core.numbers import Integer
  10. from sympy.core.relational import Equality
  11. from sympy.functions.special.tensor_functions import KroneckerDelta
  12. from sympy.core.basic import Basic
  13. from sympy.core.containers import Tuple
  14. from sympy.core.expr import Expr
  15. from sympy.core.function import (Function, Lambda)
  16. from sympy.core.mul import Mul
  17. from sympy.core.singleton import S
  18. from sympy.core.sorting import default_sort_key
  19. from sympy.core.symbol import (Dummy, Symbol)
  20. from sympy.matrices.common import MatrixCommon
  21. from sympy.matrices.expressions.diagonal import diagonalize_vector
  22. from sympy.matrices.expressions.matexpr import MatrixExpr
  23. from sympy.matrices.expressions.special import ZeroMatrix
  24. from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
  25. from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
  26. from sympy.tensor.array.ndim_array import NDimArray
  27. from sympy.tensor.indexed import (Indexed, IndexedBase)
  28. from sympy.matrices.expressions.matexpr import MatrixElement
  29. from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
  30. _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
  31. _build_push_indices_down_func_transformation
  32. from sympy.combinatorics import Permutation
  33. from sympy.combinatorics.permutations import _af_invert
  34. from sympy.core.sympify import _sympify
  35. class _ArrayExpr(Expr):
  36. shape : tTuple[Expr, ...]
  37. class ArraySymbol(_ArrayExpr):
  38. """
  39. Symbol representing an array expression
  40. """
  41. def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
  42. if isinstance(symbol, str):
  43. symbol = Symbol(symbol)
  44. # symbol = _sympify(symbol)
  45. shape = Tuple(*map(_sympify, shape))
  46. obj = Expr.__new__(cls, symbol, shape)
  47. return obj
  48. @property
  49. def name(self):
  50. return self._args[0]
  51. @property
  52. def shape(self):
  53. return self._args[1]
  54. def __getitem__(self, item):
  55. return ArrayElement(self, item)
  56. def as_explicit(self):
  57. if not all(i.is_Integer for i in self.shape):
  58. raise ValueError("cannot express explicit array with symbolic shape")
  59. data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
  60. return ImmutableDenseNDimArray(data).reshape(*self.shape)
  61. class ArrayElement(_ArrayExpr):
  62. """
  63. An element of an array.
  64. """
  65. _diff_wrt = True
  66. is_symbol = True
  67. is_commutative = True
  68. def __new__(cls, name, indices):
  69. if isinstance(name, str):
  70. name = Symbol(name)
  71. name = _sympify(name)
  72. if not isinstance(indices, collections.abc.Iterable):
  73. indices = (indices,)
  74. indices = _sympify(tuple(indices))
  75. if hasattr(name, "shape"):
  76. if any((i >= s) == True for i, s in zip(indices, name.shape)):
  77. raise ValueError("shape is out of bounds")
  78. if any((i < 0) == True for i in indices):
  79. raise ValueError("shape contains negative values")
  80. obj = Expr.__new__(cls, name, indices)
  81. return obj
  82. @property
  83. def name(self):
  84. return self._args[0]
  85. @property
  86. def indices(self):
  87. return self._args[1]
  88. def _eval_derivative(self, s):
  89. if not isinstance(s, ArrayElement):
  90. return S.Zero
  91. if s == self:
  92. return S.One
  93. if s.name != self.name:
  94. return S.Zero
  95. return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
  96. class ZeroArray(_ArrayExpr):
  97. """
  98. Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
  99. """
  100. def __new__(cls, *shape):
  101. if len(shape) == 0:
  102. return S.Zero
  103. shape = map(_sympify, shape)
  104. obj = Expr.__new__(cls, *shape)
  105. return obj
  106. @property
  107. def shape(self):
  108. return self._args
  109. def as_explicit(self):
  110. if not all(i.is_Integer for i in self.shape):
  111. raise ValueError("Cannot return explicit form for symbolic shape.")
  112. return ImmutableDenseNDimArray.zeros(*self.shape)
  113. class OneArray(_ArrayExpr):
  114. """
  115. Symbolic array of ones.
  116. """
  117. def __new__(cls, *shape):
  118. if len(shape) == 0:
  119. return S.One
  120. shape = map(_sympify, shape)
  121. obj = Expr.__new__(cls, *shape)
  122. return obj
  123. @property
  124. def shape(self):
  125. return self._args
  126. def as_explicit(self):
  127. if not all(i.is_Integer for i in self.shape):
  128. raise ValueError("Cannot return explicit form for symbolic shape.")
  129. return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
  130. class _CodegenArrayAbstract(Basic):
  131. @property
  132. def subranks(self):
  133. """
  134. Returns the ranks of the objects in the uppermost tensor product inside
  135. the current object. In case no tensor products are contained, return
  136. the atomic ranks.
  137. Examples
  138. ========
  139. >>> from sympy.tensor.array import tensorproduct, tensorcontraction
  140. >>> from sympy import MatrixSymbol
  141. >>> M = MatrixSymbol("M", 3, 3)
  142. >>> N = MatrixSymbol("N", 3, 3)
  143. >>> P = MatrixSymbol("P", 3, 3)
  144. Important: do not confuse the rank of the matrix with the rank of an array.
  145. >>> tp = tensorproduct(M, N, P)
  146. >>> tp.subranks
  147. [2, 2, 2]
  148. >>> co = tensorcontraction(tp, (1, 2), (3, 4))
  149. >>> co.subranks
  150. [2, 2, 2]
  151. """
  152. return self._subranks[:]
  153. def subrank(self):
  154. """
  155. The sum of ``subranks``.
  156. """
  157. return sum(self.subranks)
  158. @property
  159. def shape(self):
  160. return self._shape
  161. class ArrayTensorProduct(_CodegenArrayAbstract):
  162. r"""
  163. Class to represent the tensor product of array-like objects.
  164. """
  165. def __new__(cls, *args, **kwargs):
  166. args = [_sympify(arg) for arg in args]
  167. canonicalize = kwargs.pop("canonicalize", False)
  168. ranks = [get_rank(arg) for arg in args]
  169. obj = Basic.__new__(cls, *args)
  170. obj._subranks = ranks
  171. shapes = [get_shape(i) for i in args]
  172. if any(i is None for i in shapes):
  173. obj._shape = None
  174. else:
  175. obj._shape = tuple(j for i in shapes for j in i)
  176. if canonicalize:
  177. return obj._canonicalize()
  178. return obj
  179. def _canonicalize(self):
  180. args = self.args
  181. args = self._flatten(args)
  182. ranks = [get_rank(arg) for arg in args]
  183. # Check if there are nested permutation and lift them up:
  184. permutation_cycles = []
  185. for i, arg in enumerate(args):
  186. if not isinstance(arg, PermuteDims):
  187. continue
  188. permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
  189. args[i] = arg.expr
  190. if permutation_cycles:
  191. return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
  192. if len(args) == 1:
  193. return args[0]
  194. # If any object is a ZeroArray, return a ZeroArray:
  195. if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
  196. shapes = reduce(operator.add, [get_shape(i) for i in args], ())
  197. return ZeroArray(*shapes)
  198. # If there are contraction objects inside, transform the whole
  199. # expression into `ArrayContraction`:
  200. contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
  201. if contractions:
  202. ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
  203. cumulative_ranks = list(accumulate([0] + ranks))[:-1]
  204. tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
  205. contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
  206. return _array_contraction(tp, *contraction_indices)
  207. diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
  208. if diagonals:
  209. inverse_permutation = []
  210. last_perm = []
  211. ranks = [get_rank(arg) for arg in args]
  212. cumulative_ranks = list(accumulate([0] + ranks))[:-1]
  213. for i, arg in enumerate(args):
  214. if isinstance(arg, ArrayDiagonal):
  215. i1 = get_rank(arg) - len(arg.diagonal_indices)
  216. i2 = len(arg.diagonal_indices)
  217. inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
  218. last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
  219. else:
  220. inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
  221. inverse_permutation.extend(last_perm)
  222. tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
  223. ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
  224. cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
  225. diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
  226. return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
  227. return self.func(*args, canonicalize=False)
  228. def doit(self, **kwargs):
  229. deep = kwargs.get("deep", True)
  230. if deep:
  231. return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
  232. else:
  233. return self._canonicalize()
  234. @classmethod
  235. def _flatten(cls, args):
  236. args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
  237. return args
  238. def as_explicit(self):
  239. return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
  240. class ArrayAdd(_CodegenArrayAbstract):
  241. r"""
  242. Class for elementwise array additions.
  243. """
  244. def __new__(cls, *args, **kwargs):
  245. args = [_sympify(arg) for arg in args]
  246. ranks = [get_rank(arg) for arg in args]
  247. ranks = list(set(ranks))
  248. if len(ranks) != 1:
  249. raise ValueError("summing arrays of different ranks")
  250. shapes = [arg.shape for arg in args]
  251. if len({i for i in shapes if i is not None}) > 1:
  252. raise ValueError("mismatching shapes in addition")
  253. canonicalize = kwargs.pop("canonicalize", False)
  254. obj = Basic.__new__(cls, *args)
  255. obj._subranks = ranks
  256. if any(i is None for i in shapes):
  257. obj._shape = None
  258. else:
  259. obj._shape = shapes[0]
  260. if canonicalize:
  261. return obj._canonicalize()
  262. return obj
  263. def _canonicalize(self):
  264. args = self.args
  265. # Flatten:
  266. args = self._flatten_args(args)
  267. shapes = [get_shape(arg) for arg in args]
  268. args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
  269. if len(args) == 0:
  270. if any(i for i in shapes if i is None):
  271. raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
  272. return ZeroArray(*shapes[0])
  273. elif len(args) == 1:
  274. return args[0]
  275. return self.func(*args, canonicalize=False)
  276. def doit(self, **kwargs):
  277. deep = kwargs.get("deep", True)
  278. if deep:
  279. return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
  280. else:
  281. return self._canonicalize()
  282. @classmethod
  283. def _flatten_args(cls, args):
  284. new_args = []
  285. for arg in args:
  286. if isinstance(arg, ArrayAdd):
  287. new_args.extend(arg.args)
  288. else:
  289. new_args.append(arg)
  290. return new_args
  291. def as_explicit(self):
  292. return reduce(operator.add, [arg.as_explicit() for arg in self.args])
  293. class PermuteDims(_CodegenArrayAbstract):
  294. r"""
  295. Class to represent permutation of axes of arrays.
  296. Examples
  297. ========
  298. >>> from sympy.tensor.array import permutedims
  299. >>> from sympy import MatrixSymbol
  300. >>> M = MatrixSymbol("M", 3, 3)
  301. >>> cg = permutedims(M, [1, 0])
  302. The object ``cg`` represents the transposition of ``M``, as the permutation
  303. ``[1, 0]`` will act on its indices by switching them:
  304. `M_{ij} \Rightarrow M_{ji}`
  305. This is evident when transforming back to matrix form:
  306. >>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
  307. >>> convert_array_to_matrix(cg)
  308. M.T
  309. >>> N = MatrixSymbol("N", 3, 2)
  310. >>> cg = permutedims(N, [1, 0])
  311. >>> cg.shape
  312. (2, 3)
  313. Permutations of tensor products are simplified in order to achieve a
  314. standard form:
  315. >>> from sympy.tensor.array import tensorproduct
  316. >>> M = MatrixSymbol("M", 4, 5)
  317. >>> tp = tensorproduct(M, N)
  318. >>> tp.shape
  319. (4, 5, 3, 2)
  320. >>> perm1 = permutedims(tp, [2, 3, 1, 0])
  321. The args ``(M, N)`` have been sorted and the permutation has been
  322. simplified, the expression is equivalent:
  323. >>> perm1.expr.args
  324. (N, M)
  325. >>> perm1.shape
  326. (3, 2, 5, 4)
  327. >>> perm1.permutation
  328. (2 3)
  329. The permutation in its array form has been simplified from
  330. ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
  331. product `M` and `N` have been switched:
  332. >>> perm1.permutation.array_form
  333. [0, 1, 3, 2]
  334. We can nest a second permutation:
  335. >>> perm2 = permutedims(perm1, [1, 0, 2, 3])
  336. >>> perm2.shape
  337. (2, 3, 5, 4)
  338. >>> perm2.permutation.array_form
  339. [1, 0, 3, 2]
  340. """
  341. def __new__(cls, expr, permutation, **kwargs):
  342. from sympy.combinatorics import Permutation
  343. expr = _sympify(expr)
  344. permutation = Permutation(permutation)
  345. permutation_size = permutation.size
  346. expr_rank = get_rank(expr)
  347. if permutation_size != expr_rank:
  348. raise ValueError("Permutation size must be the length of the shape of expr")
  349. canonicalize = kwargs.pop("canonicalize", False)
  350. obj = Basic.__new__(cls, expr, permutation)
  351. obj._subranks = [get_rank(expr)]
  352. shape = get_shape(expr)
  353. if shape is None:
  354. obj._shape = None
  355. else:
  356. obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
  357. if canonicalize:
  358. return obj._canonicalize()
  359. return obj
  360. def _canonicalize(self):
  361. expr = self.expr
  362. permutation = self.permutation
  363. if isinstance(expr, PermuteDims):
  364. subexpr = expr.expr
  365. subperm = expr.permutation
  366. permutation = permutation * subperm
  367. expr = subexpr
  368. if isinstance(expr, ArrayContraction):
  369. expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
  370. if isinstance(expr, ArrayTensorProduct):
  371. expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
  372. if isinstance(expr, (ZeroArray, ZeroMatrix)):
  373. return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
  374. plist = permutation.array_form
  375. if plist == sorted(plist):
  376. return expr
  377. return self.func(expr, permutation, canonicalize=False)
  378. def doit(self, **kwargs):
  379. deep = kwargs.get("deep", True)
  380. if deep:
  381. return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
  382. else:
  383. return self._canonicalize()
  384. @property
  385. def expr(self):
  386. return self.args[0]
  387. @property
  388. def permutation(self):
  389. return self.args[1]
  390. @classmethod
  391. def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
  392. # Get the permutation in its image-form:
  393. perm_image_form = _af_invert(permutation.array_form)
  394. args = list(expr.args)
  395. # Starting index global position for every arg:
  396. cumul = list(accumulate([0] + expr.subranks))
  397. # Split `perm_image_form` into a list of list corresponding to the indices
  398. # of every argument:
  399. perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
  400. # Create an index, target-position-key array:
  401. ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
  402. # Sort the array according to the target-position-key:
  403. # In this way, we define a canonical way to sort the arguments according
  404. # to the permutation.
  405. ps.sort(key=lambda x: x[1])
  406. # Read the inverse-permutation (i.e. image-form) of the args:
  407. perm_args_image_form = [i[0] for i in ps]
  408. # Apply the args-permutation to the `args`:
  409. args_sorted = [args[i] for i in perm_args_image_form]
  410. # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
  411. perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
  412. new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
  413. return _array_tensor_product(*args_sorted), new_permutation
  414. @classmethod
  415. def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
  416. if not isinstance(expr, ArrayContraction):
  417. return expr, permutation
  418. if not isinstance(expr.expr, ArrayTensorProduct):
  419. return expr, permutation
  420. args = expr.expr.args
  421. subranks = [get_rank(arg) for arg in expr.expr.args]
  422. contraction_indices = expr.contraction_indices
  423. contraction_indices_flat = [j for i in contraction_indices for j in i]
  424. cumul = list(accumulate([0] + subranks))
  425. # Spread the permutation in its array form across the args in the corresponding
  426. # tensor-product arguments with free indices:
  427. permutation_array_blocks_up = []
  428. image_form = _af_invert(permutation.array_form)
  429. counter = 0
  430. for i, e in enumerate(subranks):
  431. current = []
  432. for j in range(cumul[i], cumul[i+1]):
  433. if j in contraction_indices_flat:
  434. continue
  435. current.append(image_form[counter])
  436. counter += 1
  437. permutation_array_blocks_up.append(current)
  438. # Get the map of axis repositioning for every argument of tensor-product:
  439. index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)]
  440. index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
  441. inverse_permutation = permutation**(-1)
  442. index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
  443. # Sorting key is a list of tuple, first element is the index of `args`, second element of
  444. # the tuple is the sorting key to sort `args` of the tensor product:
  445. sorting_keys = list(enumerate(index_blocks_up_permuted))
  446. sorting_keys.sort(key=lambda x: x[1])
  447. # Now we can get the permutation acting on the args in its image-form:
  448. new_perm_image_form = [i[0] for i in sorting_keys]
  449. # Apply the args-level permutation to various elements:
  450. new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
  451. new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
  452. new_args = [args[i] for i in new_perm_image_form]
  453. new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
  454. new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
  455. new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
  456. return new_expr, new_permutation
  457. @classmethod
  458. def _check_permutation_mapping(cls, expr, permutation):
  459. subranks = expr.subranks
  460. index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
  461. permuted_indices = [permutation(i) for i in range(expr.subrank())]
  462. new_args = list(expr.args)
  463. arg_candidate_index = index2arg[permuted_indices[0]]
  464. current_indices = []
  465. new_permutation = []
  466. inserted_arg_cand_indices = set([])
  467. for i, idx in enumerate(permuted_indices):
  468. if index2arg[idx] != arg_candidate_index:
  469. new_permutation.extend(current_indices)
  470. current_indices = []
  471. arg_candidate_index = index2arg[idx]
  472. current_indices.append(idx)
  473. arg_candidate_rank = subranks[arg_candidate_index]
  474. if len(current_indices) == arg_candidate_rank:
  475. new_permutation.extend(sorted(current_indices))
  476. local_current_indices = [j - min(current_indices) for j in current_indices]
  477. i1 = index2arg[i]
  478. new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
  479. inserted_arg_cand_indices.add(arg_candidate_index)
  480. current_indices = []
  481. new_permutation.extend(current_indices)
  482. # TODO: swap args positions in order to simplify the expression:
  483. # TODO: this should be in a function
  484. args_positions = list(range(len(new_args)))
  485. # Get possible shifts:
  486. maps = {}
  487. cumulative_subranks = [0] + list(accumulate(subranks))
  488. for i in range(0, len(subranks)):
  489. s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])])
  490. if len(s) != 1:
  491. continue
  492. elem = next(iter(s))
  493. if i != elem:
  494. maps[i] = elem
  495. # Find cycles in the map:
  496. lines = []
  497. current_line = []
  498. while maps:
  499. if len(current_line) == 0:
  500. k, v = maps.popitem()
  501. current_line.append(k)
  502. else:
  503. k = current_line[-1]
  504. if k not in maps:
  505. current_line = []
  506. continue
  507. v = maps.pop(k)
  508. if v in current_line:
  509. lines.append(current_line)
  510. current_line = []
  511. continue
  512. current_line.append(v)
  513. for line in lines:
  514. for i, e in enumerate(line):
  515. args_positions[line[(i + 1) % len(line)]] = e
  516. # TODO: function in order to permute the args:
  517. permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
  518. new_args = [new_args[i] for i in args_positions]
  519. new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
  520. new_permutation2 = [j for i in new_permutation_blocks for j in i]
  521. return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1)
  522. @classmethod
  523. def _check_if_there_are_closed_cycles(cls, expr, permutation):
  524. args = list(expr.args)
  525. subranks = expr.subranks
  526. cyclic_form = permutation.cyclic_form
  527. cumulative_subranks = [0] + list(accumulate(subranks))
  528. cyclic_min = [min(i) for i in cyclic_form]
  529. cyclic_max = [max(i) for i in cyclic_form]
  530. cyclic_keep = []
  531. for i, cycle in enumerate(cyclic_form):
  532. flag = True
  533. for j in range(0, len(cumulative_subranks) - 1):
  534. if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
  535. # Found a sinkable cycle.
  536. args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
  537. flag = False
  538. break
  539. if flag:
  540. cyclic_keep.append(cyclic_form[i])
  541. return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
  542. def nest_permutation(self):
  543. r"""
  544. DEPRECATED.
  545. """
  546. ret = self._nest_permutation(self.expr, self.permutation)
  547. if ret is None:
  548. return self
  549. return ret
  550. @classmethod
  551. def _nest_permutation(cls, expr, permutation):
  552. if isinstance(expr, ArrayTensorProduct):
  553. return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
  554. elif isinstance(expr, ArrayContraction):
  555. # Invert tree hierarchy: put the contraction above.
  556. cycles = permutation.cyclic_form
  557. newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
  558. newpermutation = Permutation(newcycles)
  559. new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
  560. return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
  561. elif isinstance(expr, ArrayAdd):
  562. return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
  563. return None
  564. def as_explicit(self):
  565. return permutedims(self.expr.as_explicit(), self.permutation)
  566. class ArrayDiagonal(_CodegenArrayAbstract):
  567. r"""
  568. Class to represent the diagonal operator.
  569. Explanation
  570. ===========
  571. In a 2-dimensional array it returns the diagonal, this looks like the
  572. operation:
  573. `A_{ij} \rightarrow A_{ii}`
  574. The diagonal over axes 1 and 2 (the second and third) of the tensor product
  575. of two 2-dimensional arrays `A \otimes B` is
  576. `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
  577. In this last example the array expression has been reduced from
  578. 4-dimensional to 3-dimensional. Notice that no contraction has occurred,
  579. rather there is a new index `i` for the diagonal, contraction would have
  580. reduced the array to 2 dimensions.
  581. Notice that the diagonalized out dimensions are added as new dimensions at
  582. the end of the indices.
  583. """
  584. def __new__(cls, expr, *diagonal_indices, **kwargs):
  585. expr = _sympify(expr)
  586. diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
  587. canonicalize = kwargs.get("canonicalize", False)
  588. shape = get_shape(expr)
  589. if shape is not None:
  590. cls._validate(expr, *diagonal_indices, **kwargs)
  591. # Get new shape:
  592. positions, shape = cls._get_positions_shape(shape, diagonal_indices)
  593. else:
  594. positions = None
  595. if len(diagonal_indices) == 0:
  596. return expr
  597. obj = Basic.__new__(cls, expr, *diagonal_indices)
  598. obj._positions = positions
  599. obj._subranks = _get_subranks(expr)
  600. obj._shape = shape
  601. if canonicalize:
  602. return obj._canonicalize()
  603. return obj
  604. def _canonicalize(self):
  605. expr = self.expr
  606. diagonal_indices = self.diagonal_indices
  607. trivial_diags = [i for i in diagonal_indices if len(i) == 1]
  608. if len(trivial_diags) > 0:
  609. trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
  610. diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
  611. diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
  612. rank1 = get_rank(self)
  613. rank2 = len(diagonal_indices)
  614. rank3 = rank1 - rank2
  615. inv_permutation = []
  616. counter1: int = 0
  617. indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
  618. for i in indices_down:
  619. if i in trivial_pos:
  620. inv_permutation.append(rank3 + trivial_pos[i])
  621. elif isinstance(i, (Integer, int)):
  622. inv_permutation.append(counter1)
  623. counter1 += 1
  624. else:
  625. inv_permutation.append(rank3 + diag_pos[i])
  626. permutation = _af_invert(inv_permutation)
  627. if len(diagonal_indices_short) > 0:
  628. return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
  629. else:
  630. return _permute_dims(expr, permutation)
  631. if isinstance(expr, ArrayAdd):
  632. return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
  633. if isinstance(expr, ArrayDiagonal):
  634. return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
  635. if isinstance(expr, PermuteDims):
  636. return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
  637. if isinstance(expr, (ZeroArray, ZeroMatrix)):
  638. positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
  639. return ZeroArray(*shape)
  640. return self.func(expr, *diagonal_indices, canonicalize=False)
  641. def doit(self, **kwargs):
  642. deep = kwargs.get("deep", True)
  643. if deep:
  644. return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
  645. else:
  646. return self._canonicalize()
  647. @staticmethod
  648. def _validate(expr, *diagonal_indices, **kwargs):
  649. # Check that no diagonalization happens on indices with mismatched
  650. # dimensions:
  651. shape = get_shape(expr)
  652. for i in diagonal_indices:
  653. if any(j >= len(shape) for j in i):
  654. raise ValueError("index is larger than expression shape")
  655. if len({shape[j] for j in i}) != 1:
  656. raise ValueError("diagonalizing indices of different dimensions")
  657. if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
  658. raise ValueError("need at least two axes to diagonalize")
  659. if len(set(i)) != len(i):
  660. raise ValueError("axis index cannot be repeated")
  661. @staticmethod
  662. def _remove_trivial_dimensions(shape, *diagonal_indices):
  663. return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
  664. @property
  665. def expr(self):
  666. return self.args[0]
  667. @property
  668. def diagonal_indices(self):
  669. return self.args[1:]
  670. @staticmethod
  671. def _flatten(expr, *outer_diagonal_indices):
  672. inner_diagonal_indices = expr.diagonal_indices
  673. all_inner = [j for i in inner_diagonal_indices for j in i]
  674. all_inner.sort()
  675. # TODO: add API for total rank and cumulative rank:
  676. total_rank = _get_subrank(expr)
  677. inner_rank = len(all_inner)
  678. outer_rank = total_rank - inner_rank
  679. shifts = [0 for i in range(outer_rank)]
  680. counter = 0
  681. pointer = 0
  682. for i in range(outer_rank):
  683. while pointer < inner_rank and counter >= all_inner[pointer]:
  684. counter += 1
  685. pointer += 1
  686. shifts[i] += pointer
  687. counter += 1
  688. outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
  689. diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
  690. return _array_diagonal(expr.expr, *diagonal_indices)
  691. @classmethod
  692. def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
  693. return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
  694. @classmethod
  695. def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
  696. return cls._flatten(expr, *diagonal_indices)
  697. @classmethod
  698. def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
  699. back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
  700. nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
  701. back_nondiag = [expr.permutation(i) for i in nondiag]
  702. remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
  703. new_permutation1 = [remap[i] for i in back_nondiag]
  704. shift = len(new_permutation1)
  705. diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
  706. new_permutation = new_permutation1 + diag_block_perm
  707. return _permute_dims(
  708. _array_diagonal(
  709. expr.expr,
  710. *back_diagonal_indices
  711. ),
  712. new_permutation
  713. )
  714. def _push_indices_down_nonstatic(self, indices):
  715. transform = lambda x: self._positions[x] if x < len(self._positions) else None
  716. return _apply_recursively_over_nested_lists(transform, indices)
  717. def _push_indices_up_nonstatic(self, indices):
  718. def transform(x):
  719. for i, e in enumerate(self._positions):
  720. if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
  721. return i
  722. return _apply_recursively_over_nested_lists(transform, indices)
  723. @classmethod
  724. def _push_indices_down(cls, diagonal_indices, indices, rank):
  725. positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
  726. transform = lambda x: positions[x] if x < len(positions) else None
  727. return _apply_recursively_over_nested_lists(transform, indices)
  728. @classmethod
  729. def _push_indices_up(cls, diagonal_indices, indices, rank):
  730. positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
  731. def transform(x):
  732. for i, e in enumerate(positions):
  733. if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
  734. return i
  735. return _apply_recursively_over_nested_lists(transform, indices)
  736. @classmethod
  737. def _get_positions_shape(cls, shape, diagonal_indices):
  738. data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
  739. pos1, shp1 = zip(*data1) if data1 else ((), ())
  740. data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
  741. pos2, shp2 = zip(*data2) if data2 else ((), ())
  742. positions = pos1 + pos2
  743. shape = shp1 + shp2
  744. return positions, shape
  745. def as_explicit(self):
  746. return tensordiagonal(self.expr.as_explicit(), *self.diagonal_indices)
  747. class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
  748. def __new__(cls, function, element):
  749. if not isinstance(function, Lambda):
  750. d = Dummy('d')
  751. function = Lambda(d, function(d))
  752. obj = _CodegenArrayAbstract.__new__(cls, function, element)
  753. obj._subranks = _get_subranks(element)
  754. return obj
  755. @property
  756. def function(self):
  757. return self.args[0]
  758. @property
  759. def expr(self):
  760. return self.args[1]
  761. @property
  762. def shape(self):
  763. return self.expr.shape
  764. def _get_function_fdiff(self):
  765. d = Dummy("d")
  766. function = self.function(d)
  767. fdiff = function.diff(d)
  768. if isinstance(fdiff, Function):
  769. fdiff = type(fdiff)
  770. else:
  771. fdiff = Lambda(d, fdiff)
  772. return fdiff
  773. class ArrayContraction(_CodegenArrayAbstract):
  774. r"""
  775. This class is meant to represent contractions of arrays in a form easily
  776. processable by the code printers.
  777. """
  778. def __new__(cls, expr, *contraction_indices, **kwargs):
  779. contraction_indices = _sort_contraction_indices(contraction_indices)
  780. expr = _sympify(expr)
  781. canonicalize = kwargs.get("canonicalize", False)
  782. obj = Basic.__new__(cls, expr, *contraction_indices)
  783. obj._subranks = _get_subranks(expr)
  784. obj._mapping = _get_mapping_from_subranks(obj._subranks)
  785. free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
  786. obj._free_indices_to_position = free_indices_to_position
  787. shape = get_shape(expr)
  788. cls._validate(expr, *contraction_indices)
  789. if shape:
  790. shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
  791. obj._shape = shape
  792. if canonicalize:
  793. return obj._canonicalize()
  794. return obj
  795. def _canonicalize(self):
  796. expr = self.expr
  797. contraction_indices = self.contraction_indices
  798. if len(contraction_indices) == 0:
  799. return expr
  800. if isinstance(expr, ArrayContraction):
  801. return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
  802. if isinstance(expr, (ZeroArray, ZeroMatrix)):
  803. return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
  804. if isinstance(expr, PermuteDims):
  805. return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
  806. if isinstance(expr, ArrayTensorProduct):
  807. expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
  808. expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
  809. if len(contraction_indices) == 0:
  810. return expr
  811. if isinstance(expr, ArrayDiagonal):
  812. return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
  813. if isinstance(expr, ArrayAdd):
  814. return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
  815. # Check single index contractions on 1-dimensional axes:
  816. contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
  817. if len(contraction_indices) == 0:
  818. return expr
  819. return self.func(expr, *contraction_indices, canonicalize=False)
  820. def doit(self, **kwargs):
  821. deep = kwargs.get("deep", True)
  822. if deep:
  823. return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
  824. else:
  825. return self._canonicalize()
  826. def __mul__(self, other):
  827. if other == 1:
  828. return self
  829. else:
  830. raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
  831. def __rmul__(self, other):
  832. if other == 1:
  833. return self
  834. else:
  835. raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
  836. @staticmethod
  837. def _validate(expr, *contraction_indices):
  838. shape = get_shape(expr)
  839. if shape is None:
  840. return
  841. # Check that no contraction happens when the shape is mismatched:
  842. for i in contraction_indices:
  843. if len({shape[j] for j in i if shape[j] != -1}) != 1:
  844. raise ValueError("contracting indices of different dimensions")
  845. @classmethod
  846. def _push_indices_down(cls, contraction_indices, indices):
  847. flattened_contraction_indices = [j for i in contraction_indices for j in i]
  848. flattened_contraction_indices.sort()
  849. transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
  850. return _apply_recursively_over_nested_lists(transform, indices)
  851. @classmethod
  852. def _push_indices_up(cls, contraction_indices, indices):
  853. flattened_contraction_indices = [j for i in contraction_indices for j in i]
  854. flattened_contraction_indices.sort()
  855. transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
  856. return _apply_recursively_over_nested_lists(transform, indices)
  857. @classmethod
  858. def _lower_contraction_to_addends(cls, expr, contraction_indices):
  859. if isinstance(expr, ArrayAdd):
  860. raise NotImplementedError()
  861. if not isinstance(expr, ArrayTensorProduct):
  862. return expr, contraction_indices
  863. subranks = expr.subranks
  864. cumranks = list(accumulate([0] + subranks))
  865. contraction_indices_remaining = []
  866. contraction_indices_args = [[] for i in expr.args]
  867. backshift = set([])
  868. for i, contraction_group in enumerate(contraction_indices):
  869. for j in range(len(expr.args)):
  870. if not isinstance(expr.args[j], ArrayAdd):
  871. continue
  872. if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
  873. contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
  874. backshift.update(contraction_group)
  875. break
  876. else:
  877. contraction_indices_remaining.append(contraction_group)
  878. if len(contraction_indices_remaining) == len(contraction_indices):
  879. return expr, contraction_indices
  880. total_rank = get_rank(expr)
  881. shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
  882. contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
  883. ret = _array_tensor_product(*[
  884. _array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
  885. ])
  886. return ret, contraction_indices_remaining
  887. def split_multiple_contractions(self):
  888. """
  889. Recognize multiple contractions and attempt at rewriting them as paired-contractions.
  890. This allows some contractions involving more than two indices to be
  891. rewritten as multiple contractions involving two indices, thus allowing
  892. the expression to be rewritten as a matrix multiplication line.
  893. Examples:
  894. * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
  895. Care for:
  896. - matrix being diagonalized (i.e. `A_ii`)
  897. - vectors being diagonalized (i.e. `a_i0`)
  898. Multiple contractions can be split into matrix multiplications if
  899. not more than two arguments are non-diagonals or non-vectors.
  900. Vectors get diagonalized while diagonal matrices remain diagonal.
  901. The non-diagonal matrices can be at the beginning or at the end
  902. of the final matrix multiplication line.
  903. """
  904. editor = _EditArrayContraction(self)
  905. contraction_indices = self.contraction_indices
  906. onearray_insert = []
  907. for indl, links in enumerate(contraction_indices):
  908. if len(links) <= 2:
  909. continue
  910. # Check multiple contractions:
  911. #
  912. # Examples:
  913. #
  914. # * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
  915. #
  916. # Care for:
  917. # - matrix being diagonalized (i.e. `A_ii`)
  918. # - vectors being diagonalized (i.e. `a_i0`)
  919. # Multiple contractions can be split into matrix multiplications if
  920. # not more than three arguments are non-diagonals or non-vectors.
  921. #
  922. # Vectors get diagonalized while diagonal matrices remain diagonal.
  923. # The non-diagonal matrices can be at the beginning or at the end
  924. # of the final matrix multiplication line.
  925. positions = editor.get_mapping_for_index(indl)
  926. # Also consider the case of diagonal matrices being contracted:
  927. current_dimension = self.expr.shape[links[0]]
  928. not_vectors: tTuple[_ArgE, int] = []
  929. vectors: tTuple[_ArgE, int] = []
  930. for arg_ind, rel_ind in positions:
  931. arg = editor.args_with_ind[arg_ind]
  932. mat = arg.element
  933. abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
  934. other_arg_pos = 1-rel_ind
  935. other_arg_abs = abs_arg_start + other_arg_pos
  936. if ((1 not in mat.shape) or
  937. ((current_dimension == 1) is True and mat.shape != (1, 1)) or
  938. any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
  939. ):
  940. not_vectors.append((arg, rel_ind))
  941. else:
  942. vectors.append((arg, rel_ind))
  943. if len(not_vectors) > 2:
  944. # If more than two arguments in the multiple contraction are
  945. # non-vectors and non-diagonal matrices, we cannot find a way
  946. # to split this contraction into a matrix multiplication line:
  947. continue
  948. # Three cases to handle:
  949. # - zero non-vectors
  950. # - one non-vector
  951. # - two non-vectors
  952. for v, rel_ind in vectors:
  953. v.element = diagonalize_vector(v.element)
  954. vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
  955. first_not_vector, rel_ind = vectors_to_loop[0]
  956. new_index = first_not_vector.indices[rel_ind]
  957. for v, rel_ind in vectors_to_loop[1:-1]:
  958. v.indices[rel_ind] = new_index
  959. new_index = editor.get_new_contraction_index()
  960. assert v.indices.index(None) == 1 - rel_ind
  961. v.indices[v.indices.index(None)] = new_index
  962. onearray_insert.append(v)
  963. last_vec, rel_ind = vectors_to_loop[-1]
  964. last_vec.indices[rel_ind] = new_index
  965. for v in onearray_insert:
  966. editor.insert_after(v, _ArgE(OneArray(1), [None]))
  967. return editor.to_array_contraction()
  968. def flatten_contraction_of_diagonal(self):
  969. if not isinstance(self.expr, ArrayDiagonal):
  970. return self
  971. contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
  972. new_contraction_indices = []
  973. diagonal_indices = self.expr.diagonal_indices[:]
  974. for i in contraction_down:
  975. contraction_group = list(i)
  976. for j in i:
  977. diagonal_with = [k for k in diagonal_indices if j in k]
  978. contraction_group.extend([l for k in diagonal_with for l in k])
  979. diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
  980. new_contraction_indices.append(sorted(set(contraction_group)))
  981. new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
  982. return _array_contraction(
  983. _array_diagonal(
  984. self.expr.expr,
  985. *diagonal_indices
  986. ),
  987. *new_contraction_indices
  988. )
  989. @staticmethod
  990. def _get_free_indices_to_position_map(free_indices, contraction_indices):
  991. free_indices_to_position = {}
  992. flattened_contraction_indices = [j for i in contraction_indices for j in i]
  993. counter = 0
  994. for ind in free_indices:
  995. while counter in flattened_contraction_indices:
  996. counter += 1
  997. free_indices_to_position[ind] = counter
  998. counter += 1
  999. return free_indices_to_position
  1000. @staticmethod
  1001. def _get_index_shifts(expr):
  1002. """
  1003. Get the mapping of indices at the positions before the contraction
  1004. occurs.
  1005. Examples
  1006. ========
  1007. >>> from sympy.tensor.array import tensorproduct, tensorcontraction
  1008. >>> from sympy import MatrixSymbol
  1009. >>> M = MatrixSymbol("M", 3, 3)
  1010. >>> N = MatrixSymbol("N", 3, 3)
  1011. >>> cg = tensorcontraction(tensorproduct(M, N), [1, 2])
  1012. >>> cg._get_index_shifts(cg)
  1013. [0, 2]
  1014. Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
  1015. need to be shifted by 0 and 2 to get the corresponding positions before
  1016. the contraction (that is, 0 and 3).
  1017. """
  1018. inner_contraction_indices = expr.contraction_indices
  1019. all_inner = [j for i in inner_contraction_indices for j in i]
  1020. all_inner.sort()
  1021. # TODO: add API for total rank and cumulative rank:
  1022. total_rank = _get_subrank(expr)
  1023. inner_rank = len(all_inner)
  1024. outer_rank = total_rank - inner_rank
  1025. shifts = [0 for i in range(outer_rank)]
  1026. counter = 0
  1027. pointer = 0
  1028. for i in range(outer_rank):
  1029. while pointer < inner_rank and counter >= all_inner[pointer]:
  1030. counter += 1
  1031. pointer += 1
  1032. shifts[i] += pointer
  1033. counter += 1
  1034. return shifts
  1035. @staticmethod
  1036. def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
  1037. shifts = ArrayContraction._get_index_shifts(expr)
  1038. outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
  1039. return outer_contraction_indices
  1040. @staticmethod
  1041. def _flatten(expr, *outer_contraction_indices):
  1042. inner_contraction_indices = expr.contraction_indices
  1043. outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
  1044. contraction_indices = inner_contraction_indices + outer_contraction_indices
  1045. return _array_contraction(expr.expr, *contraction_indices)
  1046. @classmethod
  1047. def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
  1048. return cls._flatten(expr, *contraction_indices)
  1049. @classmethod
  1050. def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
  1051. contraction_indices_flat = [j for i in contraction_indices for j in i]
  1052. shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
  1053. return ZeroArray(*shape)
  1054. @classmethod
  1055. def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
  1056. return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args])
  1057. @classmethod
  1058. def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
  1059. permutation = expr.permutation
  1060. plist = permutation.array_form
  1061. new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
  1062. new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
  1063. new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
  1064. return _permute_dims(
  1065. _array_contraction(expr.expr, *new_contraction_indices),
  1066. Permutation(new_plist)
  1067. )
  1068. @classmethod
  1069. def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
  1070. diagonal_indices = list(expr.diagonal_indices)
  1071. down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
  1072. # Flatten diagonally contracted indices:
  1073. down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
  1074. new_contraction_indices = []
  1075. for contr_indgrp in down_contraction_indices:
  1076. ind = contr_indgrp[:]
  1077. for j, diag_indgrp in enumerate(diagonal_indices):
  1078. if diag_indgrp is None:
  1079. continue
  1080. if any(i in diag_indgrp for i in contr_indgrp):
  1081. ind.extend(diag_indgrp)
  1082. diagonal_indices[j] = None
  1083. new_contraction_indices.append(sorted(set(ind)))
  1084. new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
  1085. new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
  1086. return _array_diagonal(
  1087. _array_contraction(expr.expr, *new_contraction_indices),
  1088. *new_diagonal_indices
  1089. )
  1090. @classmethod
  1091. def _sort_fully_contracted_args(cls, expr, contraction_indices):
  1092. if expr.shape is None:
  1093. return expr, contraction_indices
  1094. cumul = list(accumulate([0] + expr.subranks))
  1095. index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
  1096. contraction_indices_flat = {j for i in contraction_indices for j in i}
  1097. fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
  1098. new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
  1099. new_args = [expr.args[i] for i in new_pos]
  1100. new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
  1101. index_permutation_array_form = _af_invert(new_index_blocks_flat)
  1102. new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
  1103. new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
  1104. return _array_tensor_product(*new_args), new_contraction_indices
  1105. def _get_contraction_tuples(self):
  1106. r"""
  1107. Return tuples containing the argument index and position within the
  1108. argument of the index position.
  1109. Examples
  1110. ========
  1111. >>> from sympy import MatrixSymbol
  1112. >>> from sympy.abc import N
  1113. >>> from sympy.tensor.array import tensorproduct, tensorcontraction
  1114. >>> A = MatrixSymbol("A", N, N)
  1115. >>> B = MatrixSymbol("B", N, N)
  1116. >>> cg = tensorcontraction(tensorproduct(A, B), (1, 2))
  1117. >>> cg._get_contraction_tuples()
  1118. [[(0, 1), (1, 0)]]
  1119. Notes
  1120. =====
  1121. Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
  1122. of the tensor product `A\otimes B` are contracted, has been transformed
  1123. into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
  1124. notation. `(0, 1)` is the second index (1) of the first argument (i.e.
  1125. 0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
  1126. argument (i.e. 1 or `B`).
  1127. """
  1128. mapping = self._mapping
  1129. return [[mapping[j] for j in i] for i in self.contraction_indices]
  1130. @staticmethod
  1131. def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
  1132. # TODO: check that `expr` has `.subranks`:
  1133. ranks = expr.subranks
  1134. cumulative_ranks = [0] + list(accumulate(ranks))
  1135. return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
  1136. @property
  1137. def free_indices(self):
  1138. return self._free_indices[:]
  1139. @property
  1140. def free_indices_to_position(self):
  1141. return dict(self._free_indices_to_position)
  1142. @property
  1143. def expr(self):
  1144. return self.args[0]
  1145. @property
  1146. def contraction_indices(self):
  1147. return self.args[1:]
  1148. def _contraction_indices_to_components(self):
  1149. expr = self.expr
  1150. if not isinstance(expr, ArrayTensorProduct):
  1151. raise NotImplementedError("only for contractions of tensor products")
  1152. ranks = expr.subranks
  1153. mapping = {}
  1154. counter = 0
  1155. for i, rank in enumerate(ranks):
  1156. for j in range(rank):
  1157. mapping[counter] = (i, j)
  1158. counter += 1
  1159. return mapping
  1160. def sort_args_by_name(self):
  1161. """
  1162. Sort arguments in the tensor product so that their order is lexicographical.
  1163. Examples
  1164. ========
  1165. >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
  1166. >>> from sympy import MatrixSymbol
  1167. >>> from sympy.abc import N
  1168. >>> A = MatrixSymbol("A", N, N)
  1169. >>> B = MatrixSymbol("B", N, N)
  1170. >>> C = MatrixSymbol("C", N, N)
  1171. >>> D = MatrixSymbol("D", N, N)
  1172. >>> cg = convert_matrix_to_array(C*D*A*B)
  1173. >>> cg
  1174. ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
  1175. >>> cg.sort_args_by_name()
  1176. ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
  1177. """
  1178. expr = self.expr
  1179. if not isinstance(expr, ArrayTensorProduct):
  1180. return self
  1181. args = expr.args
  1182. sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
  1183. pos_sorted, args_sorted = zip(*sorted_data)
  1184. reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
  1185. contraction_tuples = self._get_contraction_tuples()
  1186. contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
  1187. c_tp = _array_tensor_product(*args_sorted)
  1188. new_contr_indices = self._contraction_tuples_to_contraction_indices(
  1189. c_tp,
  1190. contraction_tuples
  1191. )
  1192. return _array_contraction(c_tp, *new_contr_indices)
  1193. def _get_contraction_links(self):
  1194. r"""
  1195. Returns a dictionary of links between arguments in the tensor product
  1196. being contracted.
  1197. See the example for an explanation of the values.
  1198. Examples
  1199. ========
  1200. >>> from sympy import MatrixSymbol
  1201. >>> from sympy.abc import N
  1202. >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
  1203. >>> A = MatrixSymbol("A", N, N)
  1204. >>> B = MatrixSymbol("B", N, N)
  1205. >>> C = MatrixSymbol("C", N, N)
  1206. >>> D = MatrixSymbol("D", N, N)
  1207. Matrix multiplications are pairwise contractions between neighboring
  1208. matrices:
  1209. `A_{ij} B_{jk} C_{kl} D_{lm}`
  1210. >>> cg = convert_matrix_to_array(A*B*C*D)
  1211. >>> cg
  1212. ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
  1213. >>> cg._get_contraction_links()
  1214. {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
  1215. This dictionary is interpreted as follows: argument in position 0 (i.e.
  1216. matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
  1217. is argument in position 1 (matrix `B`) on the first index slot of `B`,
  1218. this is the contraction provided by the index `j` from `A`.
  1219. The argument in position 1 (that is, matrix `B`) has two contractions,
  1220. the ones provided by the indices `j` and `k`, respectively the first
  1221. and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
  1222. `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
  1223. argument in position 0 (that is, `A_{\ldot j}`), and so on.
  1224. """
  1225. args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
  1226. return dlinks
  1227. def as_explicit(self):
  1228. return tensorcontraction(self.expr.as_explicit(), *self.contraction_indices)
  1229. class Reshape(_CodegenArrayAbstract):
  1230. """
  1231. Reshape the dimensions of an array expression.
  1232. Examples
  1233. ========
  1234. >>> from sympy.tensor.array.expressions import ArraySymbol, Reshape
  1235. >>> A = ArraySymbol("A", (6,))
  1236. >>> A.shape
  1237. (6,)
  1238. >>> Reshape(A, (3, 2)).shape
  1239. (3, 2)
  1240. Check the component-explicit forms:
  1241. >>> A.as_explicit()
  1242. [A[0], A[1], A[2], A[3], A[4], A[5]]
  1243. >>> Reshape(A, (3, 2)).as_explicit()
  1244. [[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]]
  1245. """
  1246. def __new__(cls, expr, shape):
  1247. expr = _sympify(expr)
  1248. if not isinstance(shape, Tuple):
  1249. shape = Tuple(*shape)
  1250. if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False:
  1251. raise ValueError("shape mismatch")
  1252. obj = Expr.__new__(cls, expr, shape)
  1253. obj._shape = tuple(shape)
  1254. obj._expr = expr
  1255. return obj
  1256. @property
  1257. def shape(self):
  1258. return self._shape
  1259. @property
  1260. def expr(self):
  1261. return self._expr
  1262. def doit(self, *args, **kwargs):
  1263. if kwargs.get("deep", True):
  1264. expr = self.expr.doit(*args, **kwargs)
  1265. else:
  1266. expr = self.expr
  1267. if isinstance(expr, (MatrixCommon, NDimArray)):
  1268. return expr.reshape(*self.shape)
  1269. return Reshape(expr, self.shape)
  1270. def as_explicit(self):
  1271. ee = self.expr.as_explicit()
  1272. if isinstance(ee, MatrixCommon):
  1273. from sympy import Array
  1274. ee = Array(ee)
  1275. elif isinstance(ee, MatrixExpr):
  1276. return self
  1277. return ee.reshape(*self.shape)
  1278. class _ArgE:
  1279. """
  1280. The ``_ArgE`` object contains references to the array expression
  1281. (``.element``) and a list containing the information about index
  1282. contractions (``.indices``).
  1283. Index contractions are numbered and contracted indices show the number of
  1284. the contraction. Uncontracted indices have ``None`` value.
  1285. For example:
  1286. ``_ArgE(M, [None, 3])``
  1287. This object means that expression ``M`` is part of an array contraction
  1288. and has two indices, the first is not contracted (value ``None``),
  1289. the second index is contracted to the 4th (i.e. number ``3``) group of the
  1290. array contraction object.
  1291. """
  1292. indices: List[Optional[int]]
  1293. def __init__(self, element, indices: Optional[List[Optional[int]]] = None):
  1294. self.element = element
  1295. if indices is None:
  1296. self.indices = [None for i in range(get_rank(element))]
  1297. else:
  1298. self.indices = indices
  1299. def __str__(self):
  1300. return "_ArgE(%s, %s)" % (self.element, self.indices)
  1301. __repr__ = __str__
  1302. class _IndPos:
  1303. """
  1304. Index position, requiring two integers in the constructor:
  1305. - arg: the position of the argument in the tensor product,
  1306. - rel: the relative position of the index inside the argument.
  1307. """
  1308. def __init__(self, arg: int, rel: int):
  1309. self.arg = arg
  1310. self.rel = rel
  1311. def __str__(self):
  1312. return "_IndPos(%i, %i)" % (self.arg, self.rel)
  1313. __repr__ = __str__
  1314. def __iter__(self):
  1315. yield from [self.arg, self.rel]
  1316. class _EditArrayContraction:
  1317. """
  1318. Utility class to help manipulate array contraction objects.
  1319. This class takes as input an ``ArrayContraction`` object and turns it into
  1320. an editable object.
  1321. The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
  1322. which can be used to easily edit the contraction structure of the
  1323. expression.
  1324. Once editing is finished, the ``ArrayContraction`` object may be recreated
  1325. by calling the ``.to_array_contraction()`` method.
  1326. """
  1327. def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
  1328. expr: Basic
  1329. diagonalized: tTuple[tTuple[int, ...], ...]
  1330. contraction_indices: List[tTuple[int]]
  1331. if isinstance(base_array, ArrayContraction):
  1332. mapping = _get_mapping_from_subranks(base_array.subranks)
  1333. expr = base_array.expr
  1334. contraction_indices = base_array.contraction_indices
  1335. diagonalized = ()
  1336. elif isinstance(base_array, ArrayDiagonal):
  1337. if isinstance(base_array.expr, ArrayContraction):
  1338. mapping = _get_mapping_from_subranks(base_array.expr.subranks)
  1339. expr = base_array.expr.expr
  1340. diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
  1341. contraction_indices = base_array.expr.contraction_indices
  1342. elif isinstance(base_array.expr, ArrayTensorProduct):
  1343. mapping = {}
  1344. expr = base_array.expr
  1345. diagonalized = base_array.diagonal_indices
  1346. contraction_indices = []
  1347. else:
  1348. mapping = {}
  1349. expr = base_array.expr
  1350. diagonalized = base_array.diagonal_indices
  1351. contraction_indices = []
  1352. elif isinstance(base_array, ArrayTensorProduct):
  1353. expr = base_array
  1354. contraction_indices = []
  1355. diagonalized = ()
  1356. else:
  1357. raise NotImplementedError()
  1358. if isinstance(expr, ArrayTensorProduct):
  1359. args = list(expr.args)
  1360. else:
  1361. args = [expr]
  1362. args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args]
  1363. for i, contraction_tuple in enumerate(contraction_indices):
  1364. for j in contraction_tuple:
  1365. arg_pos, rel_pos = mapping[j]
  1366. args_with_ind[arg_pos].indices[rel_pos] = i
  1367. self.args_with_ind: List[_ArgE] = args_with_ind
  1368. self.number_of_contraction_indices: int = len(contraction_indices)
  1369. self._track_permutation: Optional[List[List[int]]] = None
  1370. mapping = _get_mapping_from_subranks(base_array.subranks)
  1371. # Trick: add diagonalized indices as negative indices into the editor object:
  1372. for i, e in enumerate(diagonalized):
  1373. for j in e:
  1374. arg_pos, rel_pos = mapping[j]
  1375. self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
  1376. def insert_after(self, arg: _ArgE, new_arg: _ArgE):
  1377. pos = self.args_with_ind.index(arg)
  1378. self.args_with_ind.insert(pos + 1, new_arg)
  1379. def get_new_contraction_index(self):
  1380. self.number_of_contraction_indices += 1
  1381. return self.number_of_contraction_indices - 1
  1382. def refresh_indices(self):
  1383. updates: tDict[int, int] = {}
  1384. for arg_with_ind in self.args_with_ind:
  1385. updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
  1386. for i, e in enumerate(sorted(updates)):
  1387. updates[e] = i
  1388. self.number_of_contraction_indices: int = len(updates)
  1389. for arg_with_ind in self.args_with_ind:
  1390. arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
  1391. def merge_scalars(self):
  1392. scalars = []
  1393. for arg_with_ind in self.args_with_ind:
  1394. if len(arg_with_ind.indices) == 0:
  1395. scalars.append(arg_with_ind)
  1396. for i in scalars:
  1397. self.args_with_ind.remove(i)
  1398. scalar = Mul.fromiter([i.element for i in scalars])
  1399. if len(self.args_with_ind) == 0:
  1400. self.args_with_ind.append(_ArgE(scalar))
  1401. else:
  1402. from sympy.tensor.array.expressions.conv_array_to_matrix import _a2m_tensor_product
  1403. self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
  1404. def to_array_contraction(self):
  1405. # Count the ranks of the arguments:
  1406. counter = 0
  1407. # Create a collector for the new diagonal indices:
  1408. diag_indices = defaultdict(list)
  1409. count_index_freq = Counter()
  1410. for arg_with_ind in self.args_with_ind:
  1411. count_index_freq.update(Counter(arg_with_ind.indices))
  1412. free_index_count = count_index_freq[None]
  1413. # Construct the inverse permutation:
  1414. inv_perm1 = []
  1415. inv_perm2 = []
  1416. # Keep track of which diagonal indices have already been processed:
  1417. done = set([])
  1418. # Counter for the diagonal indices:
  1419. counter4 = 0
  1420. for arg_with_ind in self.args_with_ind:
  1421. # If some diagonalization axes have been removed, they should be
  1422. # permuted in order to keep the permutation.
  1423. # Add permutation here
  1424. counter2 = 0 # counter for the indices
  1425. for i in arg_with_ind.indices:
  1426. if i is None:
  1427. inv_perm1.append(counter4)
  1428. counter2 += 1
  1429. counter4 += 1
  1430. continue
  1431. if i >= 0:
  1432. continue
  1433. # Reconstruct the diagonal indices:
  1434. diag_indices[-1 - i].append(counter + counter2)
  1435. if count_index_freq[i] == 1 and i not in done:
  1436. inv_perm1.append(free_index_count - 1 - i)
  1437. done.add(i)
  1438. elif i not in done:
  1439. inv_perm2.append(free_index_count - 1 - i)
  1440. done.add(i)
  1441. counter2 += 1
  1442. # Remove negative indices to restore a proper editor object:
  1443. arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
  1444. counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
  1445. inverse_permutation = inv_perm1 + inv_perm2
  1446. permutation = _af_invert(inverse_permutation)
  1447. # Get the diagonal indices after the detection of HadamardProduct in the expression:
  1448. diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
  1449. self.merge_scalars()
  1450. self.refresh_indices()
  1451. args = [arg.element for arg in self.args_with_ind]
  1452. contraction_indices = self.get_contraction_indices()
  1453. expr = _array_contraction(_array_tensor_product(*args), *contraction_indices)
  1454. expr2 = _array_diagonal(expr, *diag_indices_filtered)
  1455. if self._track_permutation is not None:
  1456. permutation2 = _af_invert([j for i in self._track_permutation for j in i])
  1457. expr2 = _permute_dims(expr2, permutation2)
  1458. expr3 = _permute_dims(expr2, permutation)
  1459. return expr3
  1460. def get_contraction_indices(self) -> List[List[int]]:
  1461. contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)]
  1462. current_position: int = 0
  1463. for i, arg_with_ind in enumerate(self.args_with_ind):
  1464. for j in arg_with_ind.indices:
  1465. if j is not None:
  1466. contraction_indices[j].append(current_position)
  1467. current_position += 1
  1468. return contraction_indices
  1469. def get_mapping_for_index(self, ind) -> List[_IndPos]:
  1470. if ind >= self.number_of_contraction_indices:
  1471. raise ValueError("index value exceeding the index range")
  1472. positions: List[_IndPos] = []
  1473. for i, arg_with_ind in enumerate(self.args_with_ind):
  1474. for j, arg_ind in enumerate(arg_with_ind.indices):
  1475. if ind == arg_ind:
  1476. positions.append(_IndPos(i, j))
  1477. return positions
  1478. def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]:
  1479. contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
  1480. for i, arg_with_ind in enumerate(self.args_with_ind):
  1481. for j, ind in enumerate(arg_with_ind.indices):
  1482. if ind is not None:
  1483. contraction_indices[ind].append(_IndPos(i, j))
  1484. return contraction_indices
  1485. def count_args_with_index(self, index: int) -> int:
  1486. """
  1487. Count the number of arguments that have the given index.
  1488. """
  1489. counter: int = 0
  1490. for arg_with_ind in self.args_with_ind:
  1491. if index in arg_with_ind.indices:
  1492. counter += 1
  1493. return counter
  1494. def get_args_with_index(self, index: int) -> List[_ArgE]:
  1495. """
  1496. Get a list of arguments having the given index.
  1497. """
  1498. ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
  1499. return ret
  1500. @property
  1501. def number_of_diagonal_indices(self):
  1502. data = set([])
  1503. for arg in self.args_with_ind:
  1504. data.update({i for i in arg.indices if i is not None and i < 0})
  1505. return len(data)
  1506. def track_permutation_start(self):
  1507. permutation = []
  1508. perm_diag = []
  1509. counter: int = 0
  1510. counter2: int = -1
  1511. for arg_with_ind in self.args_with_ind:
  1512. perm = []
  1513. for i in arg_with_ind.indices:
  1514. if i is not None:
  1515. if i < 0:
  1516. perm_diag.append(counter2)
  1517. counter2 -= 1
  1518. continue
  1519. perm.append(counter)
  1520. counter += 1
  1521. permutation.append(perm)
  1522. max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1
  1523. perm_diag = [max_ind - i for i in perm_diag]
  1524. self._track_permutation = permutation + [perm_diag]
  1525. def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
  1526. index_destination = self.args_with_ind.index(destination)
  1527. index_element = self.args_with_ind.index(from_element)
  1528. self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
  1529. self._track_permutation.pop(index_element) # type: ignore
  1530. def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
  1531. """
  1532. Return the range of the free indices of the arg as absolute positions
  1533. among all free indices.
  1534. """
  1535. counter = 0
  1536. for arg_with_ind in self.args_with_ind:
  1537. number_free_indices = len([i for i in arg_with_ind.indices if i is None])
  1538. if arg_with_ind == arg:
  1539. return counter, counter + number_free_indices
  1540. counter += number_free_indices
  1541. raise IndexError("argument not found")
  1542. def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
  1543. """
  1544. Return the absolute range of indices for arg, disregarding dummy
  1545. indices.
  1546. """
  1547. counter = 0
  1548. for arg_with_ind in self.args_with_ind:
  1549. number_indices = len(arg_with_ind.indices)
  1550. if arg_with_ind == arg:
  1551. return counter, counter + number_indices
  1552. counter += number_indices
  1553. raise IndexError("argument not found")
  1554. def get_rank(expr):
  1555. if isinstance(expr, (MatrixExpr, MatrixElement)):
  1556. return 2
  1557. if isinstance(expr, _CodegenArrayAbstract):
  1558. return len(expr.shape)
  1559. if isinstance(expr, NDimArray):
  1560. return expr.rank()
  1561. if isinstance(expr, Indexed):
  1562. return expr.rank
  1563. if isinstance(expr, IndexedBase):
  1564. shape = expr.shape
  1565. if shape is None:
  1566. return -1
  1567. else:
  1568. return len(shape)
  1569. if hasattr(expr, "shape"):
  1570. return len(expr.shape)
  1571. return 0
  1572. def _get_subrank(expr):
  1573. if isinstance(expr, _CodegenArrayAbstract):
  1574. return expr.subrank()
  1575. return get_rank(expr)
  1576. def _get_subranks(expr):
  1577. if isinstance(expr, _CodegenArrayAbstract):
  1578. return expr.subranks
  1579. else:
  1580. return [get_rank(expr)]
  1581. def get_shape(expr):
  1582. if hasattr(expr, "shape"):
  1583. return expr.shape
  1584. return ()
  1585. def nest_permutation(expr):
  1586. if isinstance(expr, PermuteDims):
  1587. return expr.nest_permutation()
  1588. else:
  1589. return expr
  1590. def _array_tensor_product(*args, **kwargs):
  1591. return ArrayTensorProduct(*args, canonicalize=True, **kwargs)
  1592. def _array_contraction(expr, *contraction_indices, **kwargs):
  1593. return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs)
  1594. def _array_diagonal(expr, *diagonal_indices, **kwargs):
  1595. return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs)
  1596. def _permute_dims(expr, permutation, **kwargs):
  1597. return PermuteDims(expr, permutation, canonicalize=True, **kwargs)
  1598. def _array_add(*args, **kwargs):
  1599. return ArrayAdd(*args, canonicalize=True, **kwargs)