array_expressions.py 75 KB

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