/
array_expressions.py
1967 lines (1642 loc) · 75.2 KB
/
array_expressions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections.abc
import operator
from collections import defaultdict, Counter
from functools import reduce
import itertools
from itertools import accumulate
from typing import Optional, List, Tuple as tTuple
import typing
from sympy.core.numbers import Integer
from sympy.core.relational import Equality
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import (Dummy, Symbol)
from sympy.matrices.common import MatrixCommon
from sympy.matrices.expressions.diagonal import diagonalize_vector
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
_get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
_build_push_indices_down_func_transformation
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.core.sympify import _sympify
class _ArrayExpr(Expr):
shape: tTuple[Expr, ...]
def __getitem__(self, item):
if not isinstance(item, collections.abc.Iterable):
item = (item,)
ArrayElement._check_shape(self, item)
return self._get(item)
def _get(self, item):
return _get_array_element_or_slice(self, item)
class ArraySymbol(_ArrayExpr):
"""
Symbol representing an array expression
"""
def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
if isinstance(symbol, str):
symbol = Symbol(symbol)
# symbol = _sympify(symbol)
shape = Tuple(*map(_sympify, shape))
obj = Expr.__new__(cls, symbol, shape)
return obj
@property
def name(self):
return self._args[0]
@property
def shape(self):
return self._args[1]
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("cannot express explicit array with symbolic shape")
data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
return ImmutableDenseNDimArray(data).reshape(*self.shape)
class ArrayElement(Expr):
"""
An element of an array.
"""
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, indices):
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
if not isinstance(indices, collections.abc.Iterable):
indices = (indices,)
indices = _sympify(tuple(indices))
cls._check_shape(name, indices)
obj = Expr.__new__(cls, name, indices)
return obj
@classmethod
def _check_shape(cls, name, indices):
indices = tuple(indices)
if hasattr(name, "shape"):
index_error = IndexError("number of indices does not match shape of the array")
if len(indices) != len(name.shape):
raise index_error
if any((i >= s) == True for i, s in zip(indices, name.shape)):
raise ValueError("shape is out of bounds")
if any((i < 0) == True for i in indices):
raise ValueError("shape contains negative values")
@property
def name(self):
return self._args[0]
@property
def indices(self):
return self._args[1]
def _eval_derivative(self, s):
if not isinstance(s, ArrayElement):
return S.Zero
if s == self:
return S.One
if s.name != self.name:
return S.Zero
return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
class ZeroArray(_ArrayExpr):
"""
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.Zero
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray.zeros(*self.shape)
def _get(self, item):
return S.Zero
class OneArray(_ArrayExpr):
"""
Symbolic array of ones.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.One
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
def _get(self, item):
return S.One
class _CodegenArrayAbstract(Basic):
@property
def subranks(self):
"""
Returns the ranks of the objects in the uppermost tensor product inside
the current object. In case no tensor products are contained, return
the atomic ranks.
Examples
========
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> P = MatrixSymbol("P", 3, 3)
Important: do not confuse the rank of the matrix with the rank of an array.
>>> tp = tensorproduct(M, N, P)
>>> tp.subranks
[2, 2, 2]
>>> co = tensorcontraction(tp, (1, 2), (3, 4))
>>> co.subranks
[2, 2, 2]
"""
return self._subranks[:]
def subrank(self):
"""
The sum of ``subranks``.
"""
return sum(self.subranks)
@property
def shape(self):
return self._shape
def doit(self, **hints):
deep = hints.get("deep", True)
if deep:
return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
class ArrayTensorProduct(_CodegenArrayAbstract):
r"""
Class to represent the tensor product of array-like objects.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
canonicalize = kwargs.pop("canonicalize", False)
ranks = [get_rank(arg) for arg in args]
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
shapes = [get_shape(i) for i in args]
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = tuple(j for i in shapes for j in i)
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
args = self._flatten(args)
ranks = [get_rank(arg) for arg in args]
# Check if there are nested permutation and lift them up:
permutation_cycles = []
for i, arg in enumerate(args):
if not isinstance(arg, PermuteDims):
continue
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
args[i] = arg.expr
if permutation_cycles:
return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
if len(args) == 1:
return args[0]
# If any object is a ZeroArray, return a ZeroArray:
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
return ZeroArray(*shapes)
# If there are contraction objects inside, transform the whole
# expression into `ArrayContraction`:
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
if contractions:
ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
return _array_contraction(tp, *contraction_indices)
diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
if diagonals:
inverse_permutation = []
last_perm = []
ranks = [get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
for i, arg in enumerate(args):
if isinstance(arg, ArrayDiagonal):
i1 = get_rank(arg) - len(arg.diagonal_indices)
i2 = len(arg.diagonal_indices)
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
else:
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
inverse_permutation.extend(last_perm)
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
return self.func(*args, canonicalize=False)
@classmethod
def _flatten(cls, args):
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
return args
def as_explicit(self):
return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class ArrayAdd(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError("summing arrays of different ranks")
shapes = [arg.shape for arg in args]
if len({i for i in shapes if i is not None}) > 1:
raise ValueError("mismatching shapes in addition")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = shapes[0]
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
# Flatten:
args = self._flatten_args(args)
shapes = [get_shape(arg) for arg in args]
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
if len(args) == 0:
if any(i for i in shapes if i is None):
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
return ZeroArray(*shapes[0])
elif len(args) == 1:
return args[0]
return self.func(*args, canonicalize=False)
@classmethod
def _flatten_args(cls, args):
new_args = []
for arg in args:
if isinstance(arg, ArrayAdd):
new_args.extend(arg.args)
else:
new_args.append(arg)
return new_args
def as_explicit(self):
return reduce(
operator.add,
[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class PermuteDims(_CodegenArrayAbstract):
r"""
Class to represent permutation of axes of arrays.
Examples
========
>>> from sympy.tensor.array import permutedims
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> cg = permutedims(M, [1, 0])
The object ``cg`` represents the transposition of ``M``, as the permutation
``[1, 0]`` will act on its indices by switching them:
`M_{ij} \Rightarrow M_{ji}`
This is evident when transforming back to matrix form:
>>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
>>> convert_array_to_matrix(cg)
M.T
>>> N = MatrixSymbol("N", 3, 2)
>>> cg = permutedims(N, [1, 0])
>>> cg.shape
(2, 3)
There are optional parameters that can be used as alternative to the permutation:
>>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims
>>> M = ArraySymbol("M", (1, 2, 3, 4, 5))
>>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml")
>>> expr
PermuteDims(M, (0 2 1)(3 4))
>>> expr.shape
(3, 1, 2, 5, 4)
Permutations of tensor products are simplified in order to achieve a
standard form:
>>> from sympy.tensor.array import tensorproduct
>>> M = MatrixSymbol("M", 4, 5)
>>> tp = tensorproduct(M, N)
>>> tp.shape
(4, 5, 3, 2)
>>> perm1 = permutedims(tp, [2, 3, 1, 0])
The args ``(M, N)`` have been sorted and the permutation has been
simplified, the expression is equivalent:
>>> perm1.expr.args
(N, M)
>>> perm1.shape
(3, 2, 5, 4)
>>> perm1.permutation
(2 3)
The permutation in its array form has been simplified from
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
product `M` and `N` have been switched:
>>> perm1.permutation.array_form
[0, 1, 3, 2]
We can nest a second permutation:
>>> perm2 = permutedims(perm1, [1, 0, 2, 3])
>>> perm2.shape
(2, 3, 5, 4)
>>> perm2.permutation.array_form
[1, 0, 3, 2]
"""
def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs):
from sympy.combinatorics import Permutation
expr = _sympify(expr)
expr_rank = get_rank(expr)
permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank)
permutation = Permutation(permutation)
permutation_size = permutation.size
if permutation_size != expr_rank:
raise ValueError("Permutation size must be the length of the shape of expr")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, expr, permutation)
obj._subranks = [get_rank(expr)]
shape = get_shape(expr)
if shape is None:
obj._shape = None
else:
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
permutation = self.permutation
if isinstance(expr, PermuteDims):
subexpr = expr.expr
subperm = expr.permutation
permutation = permutation * subperm
expr = subexpr
if isinstance(expr, ArrayContraction):
expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
if isinstance(expr, ArrayTensorProduct):
expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
plist = permutation.array_form
if plist == sorted(plist):
return expr
return self.func(expr, permutation, canonicalize=False)
@property
def expr(self):
return self.args[0]
@property
def permutation(self):
return self.args[1]
@classmethod
def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
# Get the permutation in its image-form:
perm_image_form = _af_invert(permutation.array_form)
args = list(expr.args)
# Starting index global position for every arg:
cumul = list(accumulate([0] + expr.subranks))
# Split `perm_image_form` into a list of list corresponding to the indices
# of every argument:
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
# Create an index, target-position-key array:
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
# Sort the array according to the target-position-key:
# In this way, we define a canonical way to sort the arguments according
# to the permutation.
ps.sort(key=lambda x: x[1])
# Read the inverse-permutation (i.e. image-form) of the args:
perm_args_image_form = [i[0] for i in ps]
# Apply the args-permutation to the `args`:
args_sorted = [args[i] for i in perm_args_image_form]
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
return _array_tensor_product(*args_sorted), new_permutation
@classmethod
def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
if not isinstance(expr, ArrayContraction):
return expr, permutation
if not isinstance(expr.expr, ArrayTensorProduct):
return expr, permutation
args = expr.expr.args
subranks = [get_rank(arg) for arg in expr.expr.args]
contraction_indices = expr.contraction_indices
contraction_indices_flat = [j for i in contraction_indices for j in i]
cumul = list(accumulate([0] + subranks))
# Spread the permutation in its array form across the args in the corresponding
# tensor-product arguments with free indices:
permutation_array_blocks_up = []
image_form = _af_invert(permutation.array_form)
counter = 0
for i, e in enumerate(subranks):
current = []
for j in range(cumul[i], cumul[i+1]):
if j in contraction_indices_flat:
continue
current.append(image_form[counter])
counter += 1
permutation_array_blocks_up.append(current)
# Get the map of axis repositioning for every argument of tensor-product:
index_blocks = [list(range(cumul[i], cumul[i+1])) for i, e in enumerate(expr.subranks)]
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
inverse_permutation = permutation**(-1)
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
# Sorting key is a list of tuple, first element is the index of `args`, second element of
# the tuple is the sorting key to sort `args` of the tensor product:
sorting_keys = list(enumerate(index_blocks_up_permuted))
sorting_keys.sort(key=lambda x: x[1])
# Now we can get the permutation acting on the args in its image-form:
new_perm_image_form = [i[0] for i in sorting_keys]
# Apply the args-level permutation to various elements:
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
new_args = [args[i] for i in new_perm_image_form]
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
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]))
return new_expr, new_permutation
@classmethod
def _check_permutation_mapping(cls, expr, permutation):
subranks = expr.subranks
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
permuted_indices = [permutation(i) for i in range(expr.subrank())]
new_args = list(expr.args)
arg_candidate_index = index2arg[permuted_indices[0]]
current_indices = []
new_permutation = []
inserted_arg_cand_indices = set()
for i, idx in enumerate(permuted_indices):
if index2arg[idx] != arg_candidate_index:
new_permutation.extend(current_indices)
current_indices = []
arg_candidate_index = index2arg[idx]
current_indices.append(idx)
arg_candidate_rank = subranks[arg_candidate_index]
if len(current_indices) == arg_candidate_rank:
new_permutation.extend(sorted(current_indices))
local_current_indices = [j - min(current_indices) for j in current_indices]
i1 = index2arg[i]
new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
inserted_arg_cand_indices.add(arg_candidate_index)
current_indices = []
new_permutation.extend(current_indices)
# TODO: swap args positions in order to simplify the expression:
# TODO: this should be in a function
args_positions = list(range(len(new_args)))
# Get possible shifts:
maps = {}
cumulative_subranks = [0] + list(accumulate(subranks))
for i in range(len(subranks)):
s = {index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])}
if len(s) != 1:
continue
elem = next(iter(s))
if i != elem:
maps[i] = elem
# Find cycles in the map:
lines = []
current_line = []
while maps:
if len(current_line) == 0:
k, v = maps.popitem()
current_line.append(k)
else:
k = current_line[-1]
if k not in maps:
current_line = []
continue
v = maps.pop(k)
if v in current_line:
lines.append(current_line)
current_line = []
continue
current_line.append(v)
for line in lines:
for i, e in enumerate(line):
args_positions[line[(i + 1) % len(line)]] = e
# TODO: function in order to permute the args:
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
new_args = [new_args[i] for i in args_positions]
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
new_permutation2 = [j for i in new_permutation_blocks for j in i]
return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1)
@classmethod
def _check_if_there_are_closed_cycles(cls, expr, permutation):
args = list(expr.args)
subranks = expr.subranks
cyclic_form = permutation.cyclic_form
cumulative_subranks = [0] + list(accumulate(subranks))
cyclic_min = [min(i) for i in cyclic_form]
cyclic_max = [max(i) for i in cyclic_form]
cyclic_keep = []
for i, cycle in enumerate(cyclic_form):
flag = True
for j in range(len(cumulative_subranks) - 1):
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
# Found a sinkable cycle.
args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
flag = False
break
if flag:
cyclic_keep.append(cyclic_form[i])
return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
def nest_permutation(self):
r"""
DEPRECATED.
"""
ret = self._nest_permutation(self.expr, self.permutation)
if ret is None:
return self
return ret
@classmethod
def _nest_permutation(cls, expr, permutation):
if isinstance(expr, ArrayTensorProduct):
return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
elif isinstance(expr, ArrayContraction):
# Invert tree hierarchy: put the contraction above.
cycles = permutation.cyclic_form
newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
newpermutation = Permutation(newcycles)
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
elif isinstance(expr, ArrayAdd):
return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
return None
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return permutedims(expr, self.permutation)
@classmethod
def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim):
if permutation is None:
if index_order_new is None or index_order_old is None:
raise ValueError("Permutation not defined")
return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim)
else:
if index_order_new is not None:
raise ValueError("index_order_new cannot be defined with permutation")
if index_order_old is not None:
raise ValueError("index_order_old cannot be defined with permutation")
return permutation
@classmethod
def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim):
if len(set(index_order_new)) != dim:
raise ValueError("wrong number of indices in index_order_new")
if len(set(index_order_old)) != dim:
raise ValueError("wrong number of indices in index_order_old")
if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0:
raise ValueError("index_order_new and index_order_old must have the same indices")
permutation = [index_order_old.index(i) for i in index_order_new]
return permutation
class ArrayDiagonal(_CodegenArrayAbstract):
r"""
Class to represent the diagonal operator.
Explanation
===========
In a 2-dimensional array it returns the diagonal, this looks like the
operation:
`A_{ij} \rightarrow A_{ii}`
The diagonal over axes 1 and 2 (the second and third) of the tensor product
of two 2-dimensional arrays `A \otimes B` is
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
In this last example the array expression has been reduced from
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
rather there is a new index `i` for the diagonal, contraction would have
reduced the array to 2 dimensions.
Notice that the diagonalized out dimensions are added as new dimensions at
the end of the indices.
"""
def __new__(cls, expr, *diagonal_indices, **kwargs):
expr = _sympify(expr)
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
canonicalize = kwargs.get("canonicalize", False)
shape = get_shape(expr)
if shape is not None:
cls._validate(expr, *diagonal_indices, **kwargs)
# Get new shape:
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
else:
positions = None
if len(diagonal_indices) == 0:
return expr
obj = Basic.__new__(cls, expr, *diagonal_indices)
obj._positions = positions
obj._subranks = _get_subranks(expr)
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
diagonal_indices = self.diagonal_indices
trivial_diags = [i for i in diagonal_indices if len(i) == 1]
if len(trivial_diags) > 0:
trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
rank1 = get_rank(self)
rank2 = len(diagonal_indices)
rank3 = rank1 - rank2
inv_permutation = []
counter1 = 0
indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
for i in indices_down:
if i in trivial_pos:
inv_permutation.append(rank3 + trivial_pos[i])
elif isinstance(i, (Integer, int)):
inv_permutation.append(counter1)
counter1 += 1
else:
inv_permutation.append(rank3 + diag_pos[i])
permutation = _af_invert(inv_permutation)
if len(diagonal_indices_short) > 0:
return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
else:
return _permute_dims(expr, permutation)
if isinstance(expr, ArrayAdd):
return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
if isinstance(expr, ArrayDiagonal):
return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
if isinstance(expr, PermuteDims):
return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
return ZeroArray(*shape)
return self.func(expr, *diagonal_indices, canonicalize=False)
@staticmethod
def _validate(expr, *diagonal_indices, **kwargs):
# Check that no diagonalization happens on indices with mismatched
# dimensions:
shape = get_shape(expr)
for i in diagonal_indices:
if any(j >= len(shape) for j in i):
raise ValueError("index is larger than expression shape")
if len({shape[j] for j in i}) != 1:
raise ValueError("diagonalizing indices of different dimensions")
if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
raise ValueError("need at least two axes to diagonalize")
if len(set(i)) != len(i):
raise ValueError("axis index cannot be repeated")
@staticmethod
def _remove_trivial_dimensions(shape, *diagonal_indices):
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
@property
def expr(self):
return self.args[0]
@property
def diagonal_indices(self):
return self.args[1:]
@staticmethod
def _flatten(expr, *outer_diagonal_indices):
inner_diagonal_indices = expr.diagonal_indices
all_inner = [j for i in inner_diagonal_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
return _array_diagonal(expr.expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
@classmethod
def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
return cls._flatten(expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
back_nondiag = [expr.permutation(i) for i in nondiag]
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
new_permutation1 = [remap[i] for i in back_nondiag]
shift = len(new_permutation1)
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
new_permutation = new_permutation1 + diag_block_perm
return _permute_dims(
_array_diagonal(
expr.expr,
*back_diagonal_indices
),
new_permutation
)
def _push_indices_down_nonstatic(self, indices):
transform = lambda x: self._positions[x] if x < len(self._positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
def _push_indices_up_nonstatic(self, indices):
def transform(x):
for i, e in enumerate(self._positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_down(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
transform = lambda x: positions[x] if x < len(positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
def transform(x):
for i, e in enumerate(positions):
if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _get_positions_shape(cls, shape, diagonal_indices):
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
pos1, shp1 = zip(*data1) if data1 else ((), ())
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
pos2, shp2 = zip(*data2) if data2 else ((), ())
positions = pos1 + pos2
shape = shp1 + shp2
return positions, shape
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return tensordiagonal(expr, *self.diagonal_indices)
class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
def __new__(cls, function, element):
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = _CodegenArrayAbstract.__new__(cls, function, element)
obj._subranks = _get_subranks(element)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return expr.applyfunc(self.function)
class ArrayContraction(_CodegenArrayAbstract):
r"""
This class is meant to represent contractions of arrays in a form easily
processable by the code printers.
"""
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
canonicalize = kwargs.get("canonicalize", False)
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
obj._free_indices_to_position = free_indices_to_position
shape = get_shape(expr)
cls._validate(expr, *contraction_indices)
if shape:
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr