array_expressions.py 75 KB

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