easy-ml 2.2.0

Machine learning library providing matrices, named tensors, linear algebra and automatic differentiation aimed at being easy to use
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
/*!
 * Einstein summation notation
 *
 * A very general purpose sum of products that can represent many
 * different tensor operations with a single notation.
 *
 * See [Einsum].
 */

use crate::numeric::{Numeric, NumericRef};
use crate::tensors::indexing::DynamicShapeIterator;
use crate::tensors::views::{TensorRef, TensorRename, TensorView};
use crate::tensors::{Dimension, Tensor};

use std::collections::HashSet;
use std::error::Error;
use std::fmt;

/**
 * Einstein summation notation
 *
 * A very general purpose sum of products that can represent many
 * different tensor operations with a single notation. In Easy-ML,
 * as tensors are already named, their dimension names are used instead
 * of arbitary characters to refer to dimensions across inputs and
 * the output.
 *
 * Whereas the typical notation used in python libraries
 * is of the form `ab,bc->ac` or `ab->` these would be
 * `Einsum::with_2(&i, &j).to(["a", "c"])` or
 * `Einsum::with_1(&i).to([])` respectively. In scenarios
 * where the existing dimension names in a tensor aren't what you
 * need for the summation notation, there are `named` helper methods
 * to provide an override, so you can perform `ab,bc->ac` with
 * input tensors of different dimension names if you write
 * `Einsum::with_2(&i, &j).named(["a", "b"], ["b", "c"]).to(["a", "c"])`.
 *
 * As with other tensor APIs, the dimension names in a Tensor must be
 * unique, so diagonal summation notation like `aa->` is not supported.
 * Dimensions names can and often will be repeated across input tensors and
 * or the output tensor shape, and each dimension name must have the same length
 * among all of these inputs. APIs will return [InconsistentDimensionLengthError]
 * if a caller passes in inconsistent arguments.
 *
 * See also
 * - [Einsum is All you Need - Einstein Summation in Deep Learning](https://rockt.ai/2018/04/30/einsum)
 * - [Einsum Is All You Need (Video)](https://www.youtube.com/watch?v=pkVwUVEHmfI)
 *
 * # You can do everything with Einsum<sup>1</sup>
 *
 * ```
 * use easy_ml::tensors::Tensor;
 * use easy_ml::tensors::views::TensorView;
 * use easy_ml::tensors::einsum::Einsum;
 *
 * // Note the length of each dimension name needs to be consistent across
 * // inputs. We know this is the case here because these are constructed examples
 * // so we just unwrap each Result from the Einsum APIs.
 * let w = Tensor::from_fn([("a", 4), ("b", 2)], |[a,b]| ((a * 2) + b) as f32);
 * let x = Tensor::from_fn([("b", 2), ("c", 3)], |[b,c]| ((b * 3) + c) as f32);
 * let y = Tensor::from_fn([("b", 2), ("c", 3), ("d", 2)], |[b,c,d]| {
 *     return ((b * 6) + (c * 2) + d) as f32
 * });
 * let z = Tensor::from_fn([("a", 4), ("c", 3)], |[a,c]| ((a * 2) + c) as f32);
 *
 * let w_transposed = TensorView::from(w.index_by(["b", "a"]));
 * assert_eq!(w_transposed, Einsum::with_1(&w).to(["b", "a"]).expect(""));
 *
 * let x_sum: f32 = x.iter().sum();
 * assert_eq!(x_sum, Einsum::with_1(&x).to([]).expect("").into_scalar());
 *
 * let multiplied = &w * &x;
 * assert_eq!(multiplied, Einsum::with_2(&w, &x).to(["a", "c"]).expect(""));
 *
 * let multiplied_2 = (&w.transpose_view(["b", "a"]) * &z).rename_owned(["b", "c"]);
 * // No need to transpose first as Einsum doesn't need the matrices ordered "b"x"a" * "a"x"c".
 * // There is a slight difference in resulting names though, as `*` drops the "a" dimension
 * // names so the output is "b"x"c", whereas we have specified the same calculation with
 * // einsum as a "b"*"c" output.
 * assert_eq!(multiplied_2, Einsum::with_2(&w, &z).to(["b", "c"]).expect(""));
 *
 * let batch_multiply = Einsum::with_3(&x, &w, &z).to(["b", "a"]).expect("");
 * ```
 *
 * - 1 - as long as you only need sums of products
 */
#[derive(Clone, Debug, Default)]
pub struct Einsum {
    _private: (),
}

impl Einsum {
    /**
     * An operation with a single input tensor, taking an input that can
     * be converted into a TensorView which includes Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     */
    pub fn with_1<T, S, I, const D: usize>(input_1: I) -> Einsum1<T, S, D>
    where
        S: TensorRef<T, D>,
        I: Into<TensorView<T, S, D>>,
    {
        Einsum1 {
            tensor_1: input_1.into(),
        }
    }

    /**
     * An operation with two input tensors, taking inputs that can
     * be converted into a TensorView which include Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     */
    pub fn with_2<T, S1, S2, I1, I2, const D1: usize, const D2: usize>(
        input_1: I1,
        input_2: I2,
    ) -> Einsum2<T, S1, S2, D1, D2>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        I1: Into<TensorView<T, S1, D1>>,
        I2: Into<TensorView<T, S2, D2>>,
    {
        Einsum2 {
            tensor_1: input_1.into(),
            tensor_2: input_2.into(),
        }
    }

    /**
     * An operation with three input tensors, taking inputs that can
     * be converted into a TensorView which include Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     */
    pub fn with_3<T, S1, S2, S3, I1, I2, I3, const D1: usize, const D2: usize, const D3: usize>(
        input_1: I1,
        input_2: I2,
        input_3: I3,
    ) -> Einsum3<T, S1, S2, S3, D1, D2, D3>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        I1: Into<TensorView<T, S1, D1>>,
        I2: Into<TensorView<T, S2, D2>>,
        I3: Into<TensorView<T, S3, D3>>,
    {
        Einsum3 {
            tensor_1: input_1.into(),
            tensor_2: input_2.into(),
            tensor_3: input_3.into(),
        }
    }

    /**
     * An operation with four input tensors, taking inputs that can
     * be converted into a TensorView which include Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     */
    pub fn with_4<
        T,
        S1,
        S2,
        S3,
        S4,
        I1,
        I2,
        I3,
        I4,
        const D1: usize,
        const D2: usize,
        const D3: usize,
        const D4: usize,
    >(
        input_1: I1,
        input_2: I2,
        input_3: I3,
        input_4: I4,
    ) -> Einsum4<T, S1, S2, S3, S4, D1, D2, D3, D4>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        I1: Into<TensorView<T, S1, D1>>,
        I2: Into<TensorView<T, S2, D2>>,
        I3: Into<TensorView<T, S3, D3>>,
        I4: Into<TensorView<T, S4, D4>>,
    {
        Einsum4 {
            tensor_1: input_1.into(),
            tensor_2: input_2.into(),
            tensor_3: input_3.into(),
            tensor_4: input_4.into(),
        }
    }

    /**
     * An operation with five input tensors, taking inputs that can
     * be converted into a TensorView which include Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     */
    pub fn with_5<
        T,
        S1,
        S2,
        S3,
        S4,
        S5,
        I1,
        I2,
        I3,
        I4,
        I5,
        const D1: usize,
        const D2: usize,
        const D3: usize,
        const D4: usize,
        const D5: usize,
    >(
        input_1: I1,
        input_2: I2,
        input_3: I3,
        input_4: I4,
        input_5: I5,
    ) -> Einsum5<T, S1, S2, S3, S4, S5, D1, D2, D3, D4, D5>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
        I1: Into<TensorView<T, S1, D1>>,
        I2: Into<TensorView<T, S2, D2>>,
        I3: Into<TensorView<T, S3, D3>>,
        I4: Into<TensorView<T, S4, D4>>,
        I5: Into<TensorView<T, S5, D5>>,
    {
        Einsum5 {
            tensor_1: input_1.into(),
            tensor_2: input_2.into(),
            tensor_3: input_3.into(),
            tensor_4: input_4.into(),
            tensor_5: input_5.into(),
        }
    }

    /**
     * An operation with six input tensors, taking inputs that can
     * be converted into a TensorView which include Tensor, &Tensor,
     * &mut Tensor as well as references to a TensorView.
     *
     * There are no technical limits on extending support to a greater number
     * of input tensors, but as it's not feasible to write a generic implementation
     * for any number of inputs at the moment we have to stop somewhere. For large
     * numbers of inputs it may often be more efficient to break down the operation
     * into substeps, such as detailed in
     * <https://optimized-einsum.readthedocs.io/en/stable/index.html>
     *
     * Until support for using an optimiser to choose an efficient contraction order
     * is added, the caller can still manually split larger operations into substeps
     * by calling Einsum multiple times with a subset of the total inputs.
     */
    pub fn with_6<
        T,
        S1,
        S2,
        S3,
        S4,
        S5,
        S6,
        I1,
        I2,
        I3,
        I4,
        I5,
        I6,
        const D1: usize,
        const D2: usize,
        const D3: usize,
        const D4: usize,
        const D5: usize,
        const D6: usize,
    >(
        input_1: I1,
        input_2: I2,
        input_3: I3,
        input_4: I4,
        input_5: I5,
        input_6: I6,
    ) -> Einsum6<T, S1, S2, S3, S4, S5, S6, D1, D2, D3, D4, D5, D6>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
        S6: TensorRef<T, D6>,
        I1: Into<TensorView<T, S1, D1>>,
        I2: Into<TensorView<T, S2, D2>>,
        I3: Into<TensorView<T, S3, D3>>,
        I4: Into<TensorView<T, S4, D4>>,
        I5: Into<TensorView<T, S5, D5>>,
        I6: Into<TensorView<T, S6, D6>>,
    {
        Einsum6 {
            tensor_1: input_1.into(),
            tensor_2: input_2.into(),
            tensor_3: input_3.into(),
            tensor_4: input_4.into(),
            tensor_5: input_5.into(),
            tensor_6: input_6.into(),
        }
    }
}

/**
 * An error indicating the lengths of dimensions with the same
 * name were inconsistent in the `I` input tensors.
 */
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InconsistentDimensionLengthError<const I: usize> {
    /**
     * The lengths of each matching dimension name in each input
     * in the same order as they were passed to the Einsum APIs.
     *
     * Some inputs may not have this dimension, so will be None.
     */
    pub lengths: [Option<usize>; I],
    /**
     * The dimension name with an inconsistency.
     */
    pub dimension: Dimension,
}

impl<const I: usize> fmt::Display for InconsistentDimensionLengthError<I> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "inconsistent dimension lengths for dimension '{}': {:?}, lengths must match when repeated in different shapes as the same dimension name",
            self.dimension,
            self.lengths,
        )
    }
}

impl<const I: usize> Error for InconsistentDimensionLengthError<I> {}

#[test]
fn test_inconsistent_dimension_length_error() {
    let error = InconsistentDimensionLengthError {
        lengths: [Some(3), None, Some(2)],
        dimension: "a",
    };
    assert_eq!(
        error.to_string(),
        "inconsistent dimension lengths for dimension 'a': [Some(3), None, Some(2)], lengths must match when repeated in different shapes as the same dimension name",
    )
}

/**
 * A single step in the contractions of an optimised Einsum calculation.
 *
 * The elements in the contraction correspond to indexes for the tensors
 * left in the overall calculation. At the first contraction, there are as many
 * tensor inputs as the number of tensors provided by the caller. For
 * example, a contraction could select the first and third tensors to perform einsum
 * on first, so would be [0, 2]. These tensors are removed from the remaining
 * inputs and we add the results of the einsum operation to the end of the list.
 * If we started with 3 tensors and selected the first and third, we would therefore
 * have two tensors remaining, the second input (now at index 0) and the intermediate
 * tensor we created (now at index 1). Therefore we could have
 * `vec![Contraction::from(vec![0, 2], Contraction::from(vec![0, 1]))]` as our
 * contraction order to split up an einsum calculation into two smaller substeps.
 */
#[allow(dead_code)]
#[derive(Clone, Debug, Eq, PartialEq)]
struct Contraction {
    tensor_indexes: Vec<usize>,
}

// Will come back to using this eventually
#[allow(dead_code)]
impl Contraction {
    /**
     * Creates a Contraction from the input indexes.
     */
    fn from(tensor_indexes: Vec<usize>) -> Contraction {
        Contraction { tensor_indexes }
    }

    /**
     * Returns a reference to the indexes in this contraction.
     */
    fn indexes(&self) -> &[usize] {
        &self.tensor_indexes
    }
}

#[allow(dead_code)]
#[derive(Clone, Debug, Eq, PartialEq)]
struct StepByStepContractionResult {
    input_shapes_left: Vec<Vec<(Dimension, usize)>>,
    contraction_output: Vec<(Dimension, usize)>,
}

/// Given already validated input such that each dimension name repeated over
/// the input_shapes_left and the output_shape share a common dimension length,
/// returns the new list of input_shapes_left and the dimension names for
/// the output of this contraction step.
///
/// Many thanks to Daniel G. A. Smith for proving assistance with understanding
/// how this step by step process is done in https://github.com/dgasmith/opt_einsum
#[allow(dead_code)]
fn step_by_step_contraction(
    input_shapes_left: &[&[(Dimension, usize)]],
    output_shape: &[(Dimension, usize)],
    contraction: &Contraction,
) -> StepByStepContractionResult {
    // 1. take the (Dimension, usize) shapes out of input_shapes_left matching the Contraction
    // These are the shapes for the tensors we're contracting.
    let contracting: Vec<&[(Dimension, usize)]> = contraction
        .tensor_indexes
        .iter()
        .map(|index| input_shapes_left[*index])
        .collect();

    // 2. make a new list for the other ones not in this contraction (might be empty)
    // These are the shapes for the tensors we'll contract later.
    let not_contracting_yet: Vec<&[(Dimension, usize)]> = input_shapes_left
        .iter()
        .enumerate()
        .filter(|(i, _)| !contraction.tensor_indexes.contains(i))
        .map(|(_, s)| *s)
        .collect();

    // 3. take the union of the dimension names from 1., preserving
    // the order they were originally in the inputs
    // These are the dimensions our contraction will be able to remove via
    // summation if they aren't needed after this step.
    let contracting_dimensions: Vec<(Dimension, usize)> = {
        let mut seen = HashSet::new();
        let mut set = Vec::new();
        for shape in &contracting {
            for d in shape.iter() {
                let new = seen.insert(*d);
                if new {
                    set.push(*d);
                }
            }
        }
        set
    };

    // 4. take the union of the dimension names from the output_shape and 2.,
    // preserving the order they were originally in the inputs
    // These are the dimensions we will still have after this step, due to
    // them being in the final output shape or just required in a later step.
    let retained_dimensions: Vec<(Dimension, usize)> = {
        let mut seen = HashSet::new();
        let mut set = Vec::new();
        for shape in &not_contracting_yet {
            for d in shape.iter() {
                let new = seen.insert(*d);
                if new {
                    set.push(*d);
                }
            }
        }
        for d in output_shape.iter() {
            let new = seen.insert(*d);
            if new {
                set.push(*d);
            }
        }
        set
    };

    // 5. take the dimension names that are in individually in both 4. and 3.
    // These are the dimensions we retain in the contraction at this
    // step.
    let contraction_output: Vec<(Dimension, usize)> = {
        let mut intersection = retained_dimensions.clone();
        intersection.retain(|shape| contracting_dimensions.contains(shape));
        intersection
    };

    // 6. add 2. and new input shape from 5., return to caller to become new input_shapes_left
    // These are the shapes of the tensors left to be contracted
    // in later steps. This will eventually be a single element list
    // matching the output shape when we complete the final step.
    let new_input_shapes_left = {
        let mut vec = Vec::with_capacity(not_contracting_yet.len() + 1);
        for d in not_contracting_yet.iter() {
            vec.push(d.to_vec());
        }
        vec.push(contraction_output.clone());
        vec
    };

    StepByStepContractionResult {
        contraction_output,
        input_shapes_left: new_input_shapes_left,
    }
}

/// Return length of matching dimension in inputs, and error if the length of
/// this output dimension is inconsistent in the input.
fn length_of<const I: usize>(
    output_dimension: Dimension,
    input: &[&[(Dimension, usize)]; I],
) -> Result<usize, InconsistentDimensionLengthError<I>> {
    let lengths = input.map(|shapes| {
        shapes
            .iter()
            .find(|(dimension, _length)| *dimension == output_dimension)
            .map(|(_dimension, length)| *length)
    });

    let first_length = lengths.iter().filter_map(|l| *l).next();
    if let Some(length) = first_length {
        // Check other lengths agree
        if lengths.iter().any(|l| l.is_some() && *l != Some(length)) {
            // Different length matches
            Err(InconsistentDimensionLengthError {
                lengths,
                dimension: output_dimension,
            })
        } else {
            Ok(length)
        }
    } else {
        // No matching lengths, we needed 1 match
        Err(InconsistentDimensionLengthError {
            lengths,
            dimension: output_dimension,
        })
    }
}

#[track_caller]
fn tensor_with_name<T, I, S, const D: usize>(
    dimensions: [Dimension; D],
    tensor: I,
) -> TensorView<T, TensorRename<T, S, D>, D>
where
    I: Into<TensorView<T, S, D>>,
    S: TensorRef<T, D>,
{
    let source: S = tensor.into().source();
    let with_names = TensorRename::from(source, dimensions);
    TensorView::from(with_names)
}

/// Return required output shape given input shape sizes and output shape
/// dimension names. This can fail if a dimension in the requested output
/// shape isn't present in the input, or if the input has contradictory sizes
/// for it.
// We could validate some parts of the input earlier than when we have
// the output dimensions, but validating tensor lengths are consistent for
// each common input dimension name would happen multiple times in the scenario
// of a user using the `named` helper method, so it's a lot easier to use the API
// if we defer validation till the final method call.
fn output_shape_for<const I: usize, const O: usize>(
    input: &[&[(Dimension, usize)]; I],
    output: &[Dimension; O],
) -> Result<[(Dimension, usize); O], InconsistentDimensionLengthError<I>> {
    let mut output_shape = std::array::from_fn(|d| (output[d], 0));
    for x in output_shape.iter_mut() {
        x.1 = length_of(x.0, input)?;
    }
    Ok(output_shape)
}

/// We sum over every dimension included in the input and not the output
///
/// Returns a vec of the summation dimensions along with their validated
/// lengths, and errors if the lengths of any summation dimensions in
/// the input are inconsistent.
fn summation_dimensions<const I: usize, const O: usize>(
    input: &[&[(Dimension, usize)]; I],
    output: &[Dimension; O],
) -> Result<Vec<(Dimension, usize)>, InconsistentDimensionLengthError<I>> {
    let mut total_dimensions = 0;
    for shape in input {
        total_dimensions += shape.len();
    }

    // Worst case is every dimension in each input tensor
    // has unique dimensions
    let mut unique_dimensions = Vec::with_capacity(total_dimensions);

    for shape in input {
        for (dimension, length) in shape.iter() {
            if output.contains(dimension) {
                // If this dimension is requested in the output we will be checking
                // for consistent lengths in `length_of` and this dimension won't be
                // a summation dimension so we can ignore it here.
                continue;
            }
            let existing = unique_dimensions.iter().find(|(d, _)| d == dimension);
            match existing {
                None => unique_dimensions.push((*dimension, *length)),
                Some((_, l)) => {
                    if length != l {
                        // Inconsistent lengths
                        return Err(InconsistentDimensionLengthError {
                            lengths: std::array::from_fn(|i| {
                                input[i]
                                    .iter()
                                    .find(|(d, _)| d == dimension)
                                    .map(|(_, l)| *l)
                            }),
                            dimension,
                        });
                    }
                }
            }
        }
    }

    Ok(unique_dimensions)
}

/// Filters outer indexes to only the matching dimensions
/// for the input shape. Panics if any dimensions in the
/// input shape are missing from the outer slices, but accepts
/// more indexes and dimensions in the outer slices than
/// actually needed for the input shape without any errors.
fn filter_outer_indexes<const D: usize, const O: usize>(
    outer_indexes: &[usize; O],
    outer_shape: &[(Dimension, usize); O],
    input_shape: &[(Dimension, usize); D],
) -> [usize; D] {
    let mut input_indexes = [0; D];
    for d in 0..D {
        let mut found = false;
        let dimension = input_shape[d].0;
        for o in 0..O {
            let possible_dimension = outer_shape[o].0;
            if possible_dimension == dimension {
                input_indexes[d] = outer_indexes[o];
                found = true;
                break;
            }
        }
        if !found {
            panic!(
                "Expected to find an index for dimension {:?} but was not present in {:?} for {:?} while trying to index tensor of shape {:?}",
                dimension,
                outer_indexes,
                outer_shape,
                input_shape,
            );
        }
    }
    input_indexes
}

/// Filters outer indexes and summation indexes to only the
/// matching dimensions for the input shape. Panics if any dimensions
/// in the input shape are missing from the outer and summation slices,
/// but accepts more indexes and dimensions in the outer and summation
/// slices than actually needed for the input shape without any errors.
/// Summation slices must be the same length, we just don't know their
/// length at compile time so can't enforce it in the type system.
fn filter_outer_and_summation_indexes<const D: usize, const O: usize>(
    outer_indexes: &[usize; O],
    outer_shape: &[(Dimension, usize); O],
    summation_indexes: &[usize],
    summation_shape: &[(Dimension, usize)],
    input_shape: &[(Dimension, usize); D],
) -> [usize; D] {
    let mut input_indexes = [0; D];
    for d in 0..D {
        let mut found = false;
        let dimension = input_shape[d].0;
        for o in 0..O {
            let possible_dimension = outer_shape[o].0;
            if possible_dimension == dimension {
                input_indexes[d] = outer_indexes[o];
                found = true;
                break;
            }
        }
        let summation_iter = summation_indexes.iter().zip(summation_shape.iter());
        for (index, (possible_dimension, _length)) in summation_iter {
            if *possible_dimension == dimension {
                input_indexes[d] = *index;
                found = true;
                break;
            }
        }
        if !found {
            panic!(
                "Expected to find an index for dimension {:?} but was not present in {:?} for {:?} or {:?} for {:?} while trying to index tensor of shape {:?}",
                dimension,
                outer_indexes,
                outer_shape,
                summation_indexes,
                summation_shape,
                input_shape,
            );
        }
    }
    input_indexes
}

/**
 * Einstein summation notation operation with a single input tensor.
 */
pub struct Einsum1<T, S1, const D1: usize> {
    tensor_1: TensorView<T, S1, D1>,
}

/**
 * Einstein summation notation operation with two input tensors.
 */
pub struct Einsum2<T, S1, S2, const D1: usize, const D2: usize> {
    tensor_1: TensorView<T, S1, D1>,
    tensor_2: TensorView<T, S2, D2>,
}

/**
 * Einstein summation notation operation with three input tensors
 */
pub struct Einsum3<T, S1, S2, S3, const D1: usize, const D2: usize, const D3: usize> {
    tensor_1: TensorView<T, S1, D1>,
    tensor_2: TensorView<T, S2, D2>,
    tensor_3: TensorView<T, S3, D3>,
}

/**
 * Einstein summation notation operation with four input tensors
 */
pub struct Einsum4<
    T,
    S1,
    S2,
    S3,
    S4,
    const D1: usize,
    const D2: usize,
    const D3: usize,
    const D4: usize,
> {
    tensor_1: TensorView<T, S1, D1>,
    tensor_2: TensorView<T, S2, D2>,
    tensor_3: TensorView<T, S3, D3>,
    tensor_4: TensorView<T, S4, D4>,
}

/**
 * Einstein summation notation operation with five input tensors
 */
pub struct Einsum5<
    T,
    S1,
    S2,
    S3,
    S4,
    S5,
    const D1: usize,
    const D2: usize,
    const D3: usize,
    const D4: usize,
    const D5: usize,
> {
    tensor_1: TensorView<T, S1, D1>,
    tensor_2: TensorView<T, S2, D2>,
    tensor_3: TensorView<T, S3, D3>,
    tensor_4: TensorView<T, S4, D4>,
    tensor_5: TensorView<T, S5, D5>,
}

/**
 * Einstein summation notation operation with six input tensors
 *
 * There are no technical limits on extending support to a greater number
 * of input tensors, but as it's not feasible to write a generic implementation
 * for any number of inputs at the moment we have to stop somewhere. For large
 * numbers of inputs it may often be more efficient to break down the operation
 * into substeps, such as detailed in
 * <https://optimized-einsum.readthedocs.io/en/stable/index.html>
 *
 * Until support for using an optimiser to choose an efficient contraction order
 * is added, the caller can still manually split larger operations into substeps
 * by calling Einsum multiple times with a subset of the total inputs.
 */
pub struct Einsum6<
    T,
    S1,
    S2,
    S3,
    S4,
    S5,
    S6,
    const D1: usize,
    const D2: usize,
    const D3: usize,
    const D4: usize,
    const D5: usize,
    const D6: usize,
> {
    tensor_1: TensorView<T, S1, D1>,
    tensor_2: TensorView<T, S2, D2>,
    tensor_3: TensorView<T, S3, D3>,
    tensor_4: TensorView<T, S4, D4>,
    tensor_5: TensorView<T, S5, D5>,
    tensor_6: TensorView<T, S6, D6>,
}

impl<T, S1, const D1: usize> Einsum1<T, S1, D1> {
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    pub fn named(self, input_1: [Dimension; D1]) -> Einsum1<T, TensorRename<T, S1, D1>, D1>
    where
        S1: TensorRef<T, D1>,
    {
        Einsum1 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<1>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input = &[input_1_shape];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                sum = sum + product_1;
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            sum = sum + product_1;
                        }
                        None => break,
                    }
                }
            }
            *element = sum;
        }

        Ok(output_tensor)
    }
}

impl<T, S1, S2, const D1: usize, const D2: usize> Einsum2<T, S1, S2, D1, D2> {
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    pub fn named(
        self,
        input_1: [Dimension; D1],
        input_2: [Dimension; D2],
    ) -> Einsum2<T, TensorRename<T, S1, D1>, TensorRename<T, S2, D2>, D1, D2>
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
    {
        Einsum2 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
            tensor_2: tensor_with_name(input_2, self.tensor_2),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<2>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input_2_shape_const = &self.tensor_2.shape();
        let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
        let input = &[input_1_shape, input_2_shape];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();
        let tensor_2_indexing = self.tensor_2.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                let product_2 = tensor_2_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_2_shape_const,
                ));
                sum = sum + (product_1 * product_2);
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            let product_2 =
                                tensor_2_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_2_shape_const,
                                ));
                            sum = sum + (product_1 * product_2);
                        }
                        None => break,
                    }
                }
            }

            *element = sum;
        }

        Ok(output_tensor)
    }
}

impl<T, S1, S2, S3, const D1: usize, const D2: usize, const D3: usize>
    Einsum3<T, S1, S2, S3, D1, D2, D3>
{
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    #[allow(clippy::type_complexity)]
    pub fn named(
        self,
        input_1: [Dimension; D1],
        input_2: [Dimension; D2],
        input_3: [Dimension; D3],
    ) -> Einsum3<
        T,
        TensorRename<T, S1, D1>,
        TensorRename<T, S2, D2>,
        TensorRename<T, S3, D3>,
        D1,
        D2,
        D3,
    >
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
    {
        Einsum3 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
            tensor_2: tensor_with_name(input_2, self.tensor_2),
            tensor_3: tensor_with_name(input_3, self.tensor_3),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<3>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input_2_shape_const = &self.tensor_2.shape();
        let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
        let input_3_shape_const = &self.tensor_3.shape();
        let input_3_shape: &[(Dimension, usize)] = input_3_shape_const;
        let input = &[input_1_shape, input_2_shape, input_3_shape];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();
        let tensor_2_indexing = self.tensor_2.index();
        let tensor_3_indexing = self.tensor_3.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                let product_2 = tensor_2_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_2_shape_const,
                ));
                let product_3 = tensor_3_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_3_shape_const,
                ));
                sum = sum + (product_1 * product_2 * product_3);
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            let product_2 =
                                tensor_2_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_2_shape_const,
                                ));
                            let product_3 =
                                tensor_3_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_3_shape_const,
                                ));
                            sum = sum + (product_1 * product_2 * product_3);
                        }
                        None => break,
                    }
                }
            }

            *element = sum;
        }

        Ok(output_tensor)
    }
}

impl<T, S1, S2, S3, S4, const D1: usize, const D2: usize, const D3: usize, const D4: usize>
    Einsum4<T, S1, S2, S3, S4, D1, D2, D3, D4>
{
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    #[allow(clippy::type_complexity)]
    pub fn named(
        self,
        input_1: [Dimension; D1],
        input_2: [Dimension; D2],
        input_3: [Dimension; D3],
        input_4: [Dimension; D4],
    ) -> Einsum4<
        T,
        TensorRename<T, S1, D1>,
        TensorRename<T, S2, D2>,
        TensorRename<T, S3, D3>,
        TensorRename<T, S4, D4>,
        D1,
        D2,
        D3,
        D4,
    >
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
    {
        Einsum4 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
            tensor_2: tensor_with_name(input_2, self.tensor_2),
            tensor_3: tensor_with_name(input_3, self.tensor_3),
            tensor_4: tensor_with_name(input_4, self.tensor_4),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<4>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input_2_shape_const = &self.tensor_2.shape();
        let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
        let input_3_shape_const = &self.tensor_3.shape();
        let input_3_shape: &[(Dimension, usize)] = input_3_shape_const;
        let input_4_shape_const = &self.tensor_4.shape();
        let input_4_shape: &[(Dimension, usize)] = input_4_shape_const;
        let input = &[input_1_shape, input_2_shape, input_3_shape, input_4_shape];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();
        let tensor_2_indexing = self.tensor_2.index();
        let tensor_3_indexing = self.tensor_3.index();
        let tensor_4_indexing = self.tensor_4.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                let product_2 = tensor_2_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_2_shape_const,
                ));
                let product_3 = tensor_3_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_3_shape_const,
                ));
                let product_4 = tensor_4_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_4_shape_const,
                ));
                sum = sum + (product_1 * product_2 * product_3 * product_4);
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            let product_2 =
                                tensor_2_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_2_shape_const,
                                ));
                            let product_3 =
                                tensor_3_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_3_shape_const,
                                ));
                            let product_4 =
                                tensor_4_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_4_shape_const,
                                ));
                            sum = sum + (product_1 * product_2 * product_3 * product_4);
                        }
                        None => break,
                    }
                }
            }

            *element = sum;
        }

        Ok(output_tensor)
    }
}

impl<
        T,
        S1,
        S2,
        S3,
        S4,
        S5,
        const D1: usize,
        const D2: usize,
        const D3: usize,
        const D4: usize,
        const D5: usize,
    > Einsum5<T, S1, S2, S3, S4, S5, D1, D2, D3, D4, D5>
{
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    #[allow(clippy::type_complexity)]
    pub fn named(
        self,
        input_1: [Dimension; D1],
        input_2: [Dimension; D2],
        input_3: [Dimension; D3],
        input_4: [Dimension; D4],
        input_5: [Dimension; D5],
    ) -> Einsum5<
        T,
        TensorRename<T, S1, D1>,
        TensorRename<T, S2, D2>,
        TensorRename<T, S3, D3>,
        TensorRename<T, S4, D4>,
        TensorRename<T, S5, D5>,
        D1,
        D2,
        D3,
        D4,
        D5,
    >
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
    {
        Einsum5 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
            tensor_2: tensor_with_name(input_2, self.tensor_2),
            tensor_3: tensor_with_name(input_3, self.tensor_3),
            tensor_4: tensor_with_name(input_4, self.tensor_4),
            tensor_5: tensor_with_name(input_5, self.tensor_5),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<5>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input_2_shape_const = &self.tensor_2.shape();
        let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
        let input_3_shape_const = &self.tensor_3.shape();
        let input_3_shape: &[(Dimension, usize)] = input_3_shape_const;
        let input_4_shape_const = &self.tensor_4.shape();
        let input_4_shape: &[(Dimension, usize)] = input_4_shape_const;
        let input_5_shape_const = &self.tensor_5.shape();
        let input_5_shape: &[(Dimension, usize)] = input_5_shape_const;
        let input = &[
            input_1_shape,
            input_2_shape,
            input_3_shape,
            input_4_shape,
            input_5_shape,
        ];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();
        let tensor_2_indexing = self.tensor_2.index();
        let tensor_3_indexing = self.tensor_3.index();
        let tensor_4_indexing = self.tensor_4.index();
        let tensor_5_indexing = self.tensor_5.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                let product_2 = tensor_2_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_2_shape_const,
                ));
                let product_3 = tensor_3_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_3_shape_const,
                ));
                let product_4 = tensor_4_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_4_shape_const,
                ));
                let product_5 = tensor_5_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_5_shape_const,
                ));
                sum = sum + (product_1 * product_2 * product_3 * product_4 * product_5);
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            let product_2 =
                                tensor_2_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_2_shape_const,
                                ));
                            let product_3 =
                                tensor_3_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_3_shape_const,
                                ));
                            let product_4 =
                                tensor_4_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_4_shape_const,
                                ));
                            let product_5 =
                                tensor_5_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_5_shape_const,
                                ));
                            sum = sum + (product_1 * product_2 * product_3 * product_4 * product_5);
                        }
                        None => break,
                    }
                }
            }

            *element = sum;
        }

        Ok(output_tensor)
    }
}

impl<
        T,
        S1,
        S2,
        S3,
        S4,
        S5,
        S6,
        const D1: usize,
        const D2: usize,
        const D3: usize,
        const D4: usize,
        const D5: usize,
        const D6: usize,
    > Einsum6<T, S1, S2, S3, S4, S5, S6, D1, D2, D3, D4, D5, D6>
{
    /**
     * Renames all input tensors to the new names. Their shapes will
     * still be in the same order with the same lengths of data, as
     * per [TensorRename]. As per TensorRename, dimension names for
     * each individual tensor must be unique.
     */
    #[track_caller]
    #[allow(clippy::type_complexity)]
    pub fn named(
        self,
        input_1: [Dimension; D1],
        input_2: [Dimension; D2],
        input_3: [Dimension; D3],
        input_4: [Dimension; D4],
        input_5: [Dimension; D5],
        input_6: [Dimension; D6],
    ) -> Einsum6<
        T,
        TensorRename<T, S1, D1>,
        TensorRename<T, S2, D2>,
        TensorRename<T, S3, D3>,
        TensorRename<T, S4, D4>,
        TensorRename<T, S5, D5>,
        TensorRename<T, S6, D6>,
        D1,
        D2,
        D3,
        D4,
        D5,
        D6,
    >
    where
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
        S6: TensorRef<T, D6>,
    {
        Einsum6 {
            tensor_1: tensor_with_name(input_1, self.tensor_1),
            tensor_2: tensor_with_name(input_2, self.tensor_2),
            tensor_3: tensor_with_name(input_3, self.tensor_3),
            tensor_4: tensor_with_name(input_4, self.tensor_4),
            tensor_5: tensor_with_name(input_5, self.tensor_5),
            tensor_6: tensor_with_name(input_6, self.tensor_6),
        }
    }

    pub fn to<const O: usize>(
        self,
        output: [Dimension; O],
    ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<6>>
    where
        T: Numeric,
        for<'a> &'a T: NumericRef<T>,
        S1: TensorRef<T, D1>,
        S2: TensorRef<T, D2>,
        S3: TensorRef<T, D3>,
        S4: TensorRef<T, D4>,
        S5: TensorRef<T, D5>,
        S6: TensorRef<T, D6>,
    {
        let input_1_shape_const = &self.tensor_1.shape();
        let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
        let input_2_shape_const = &self.tensor_2.shape();
        let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
        let input_3_shape_const = &self.tensor_3.shape();
        let input_3_shape: &[(Dimension, usize)] = input_3_shape_const;
        let input_4_shape_const = &self.tensor_4.shape();
        let input_4_shape: &[(Dimension, usize)] = input_4_shape_const;
        let input_5_shape_const = &self.tensor_5.shape();
        let input_5_shape: &[(Dimension, usize)] = input_5_shape_const;
        let input_6_shape_const = &self.tensor_6.shape();
        let input_6_shape: &[(Dimension, usize)] = input_6_shape_const;
        let input = &[
            input_1_shape,
            input_2_shape,
            input_3_shape,
            input_4_shape,
            input_5_shape,
            input_6_shape,
        ];

        let output_shape = output_shape_for(input, &output)?;
        let mut output_tensor = Tensor::empty(output_shape, T::zero());

        let summation_dimensions = summation_dimensions(input, &output)?;
        let tensor_1_indexing = self.tensor_1.index();
        let tensor_2_indexing = self.tensor_2.index();
        let tensor_3_indexing = self.tensor_3.index();
        let tensor_4_indexing = self.tensor_4.index();
        let tensor_5_indexing = self.tensor_5.index();
        let tensor_6_indexing = self.tensor_6.index();

        for (indexes, element) in output_tensor.index_mut().iter_reference_mut().with_index() {
            let mut sum = T::zero();

            if summation_dimensions.is_empty() {
                let product_1 = tensor_1_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_1_shape_const,
                ));
                let product_2 = tensor_2_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_2_shape_const,
                ));
                let product_3 = tensor_3_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_3_shape_const,
                ));
                let product_4 = tensor_4_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_4_shape_const,
                ));
                let product_5 = tensor_5_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_5_shape_const,
                ));
                let product_6 = tensor_6_indexing.get_ref(filter_outer_indexes(
                    &indexes,
                    &output_shape,
                    input_6_shape_const,
                ));
                sum = sum + (product_1 * product_2 * product_3 * product_4 * product_5 * product_6);
            } else {
                let mut summation_iterator = DynamicShapeIterator::from(&summation_dimensions);
                loop {
                    let next = summation_iterator.next();
                    match next {
                        Some(summation_indexes) => {
                            let product_1 =
                                tensor_1_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_1_shape_const,
                                ));
                            let product_2 =
                                tensor_2_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_2_shape_const,
                                ));
                            let product_3 =
                                tensor_3_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_3_shape_const,
                                ));
                            let product_4 =
                                tensor_4_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_4_shape_const,
                                ));
                            let product_5 =
                                tensor_5_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_5_shape_const,
                                ));
                            let product_6 =
                                tensor_6_indexing.get_ref(filter_outer_and_summation_indexes(
                                    &indexes,
                                    &output_shape,
                                    summation_indexes,
                                    &summation_dimensions,
                                    input_6_shape_const,
                                ));
                            sum = sum
                                + (product_1
                                    * product_2
                                    * product_3
                                    * product_4
                                    * product_5
                                    * product_6);
                        }
                        None => break,
                    }
                }
            }

            *element = sum;
        }

        Ok(output_tensor)
    }
}

#[test]
fn step_by_step_contraction_tests() {
    // Simple case where we just contract 2 tensors and consume all the input
    assert_eq!(
        step_by_step_contraction(
            &[&[("x", 2), ("y", 3)], &[("y", 3), ("z", 4)]],
            &[("x", 2), ("z", 4)],
            &Contraction {
                tensor_indexes: vec![0, 1]
            },
        ),
        StepByStepContractionResult {
            input_shapes_left: vec![vec![("x", 2), ("z", 4)]],
            contraction_output: vec![("x", 2), ("z", 4)],
        }
    );
    // Case where we contract out `b` and `d` and leave just two tensors
    // with `a` and `c` terms to contract next.
    #[rustfmt::skip]
    assert_eq!(
        step_by_step_contraction(
            &[
                &[("a", 2), ("b", 3), ("d", 5)],
                &[("a", 2), ("c", 4)],
                &[("b", 3), ("d", 5), ("c", 4)],
            ],
            &[("a", 2), ("c", 4)],
            &Contraction {
                tensor_indexes: vec![0, 2]
            },
        ),
        StepByStepContractionResult {
            input_shapes_left: vec![
                vec![("a", 2), ("c", 4)],
                vec![("a", 2), ("c", 4)],
            ],
            contraction_output: vec![("a", 2), ("c", 4)],
        }
    );
    // Less optimised route where we have to leave `b` and `d` terms in
    // because the last input still needs them, and we can't contract out
    // `a` because we requested it in the output.
    assert_eq!(
        step_by_step_contraction(
            &[
                &[("a", 2), ("b", 3), ("d", 5)],
                &[("a", 2), ("c", 4)],
                &[("b", 3), ("d", 5), ("c", 4)],
            ],
            &[("a", 2), ("c", 4)],
            &Contraction {
                tensor_indexes: vec![0, 1]
            },
        ),
        StepByStepContractionResult {
            input_shapes_left: vec![
                vec![("b", 3), ("d", 5), ("c", 4)],
                vec![("b", 3), ("d", 5), ("c", 4), ("a", 2)],
            ],
            contraction_output: vec![("b", 3), ("d", 5), ("c", 4), ("a", 2)],
        }
    );
    // Slightly different route where we can contract out `a` because
    // we didn't request it in the output.
    assert_eq!(
        step_by_step_contraction(
            &[
                &[("a", 2), ("b", 3), ("d", 5)],
                &[("a", 2), ("c", 4)],
                &[("b", 3), ("d", 5), ("c", 4)],
            ],
            &[("c", 4)],
            &Contraction {
                tensor_indexes: vec![0, 1]
            },
        ),
        StepByStepContractionResult {
            input_shapes_left: vec![
                vec![("b", 3), ("d", 5), ("c", 4)],
                vec![("b", 3), ("d", 5), ("c", 4)],
            ],
            contraction_output: vec![("b", 3), ("d", 5), ("c", 4)],
        }
    );
}

// TODO: Letting caller pass in the desired contraction order
// should largely build on top of naive Einsum implementation, but we
// are going to need quite a few more APIs to generalise over different
// dimensionalities of tensors first since we have to erase dimension length
// and dimension arguments somehow.
// fn by_contraction_order<const O: usize>(
//     self,
//     output: [Dimension; O],
//     contraction_order: &[Contraction],
// ) -> Result<Tensor<T, O>, InconsistentDimensionLengthError<3>>
// where
//     T: Numeric,
//     for<'a> &'a T: NumericRef<T>,
//     S1: TensorRef<T, D1>,
//     S2: TensorRef<T, D2>,
//     S3: TensorRef<T, D3>,
// {
//     let input_1_shape_const = &self.tensor_1.shape();
//     let input_1_shape: &[(Dimension, usize)] = input_1_shape_const;
//     let input_2_shape_const = &self.tensor_2.shape();
//     let input_2_shape: &[(Dimension, usize)] = input_2_shape_const;
//     let input_3_shape_const = &self.tensor_3.shape();
//     let input_3_shape: &[(Dimension, usize)] = input_3_shape_const;
//     let input = &[input_1_shape, input_2_shape, input_3_shape];
//
//     let output_shape = output_shape_for(input, &output)?;
//     let mut output_tensor = Tensor::empty(output_shape, T::zero());
//
//     let summation_dimensions = summation_dimensions(input, &output)?;
//
//     let mut input: Vec<Vec<(Dimension, usize)>> = input.iter().map(|i| i.to_vec()).collect();
//
//     for contraction in contraction_order.iter() {
//         let step = step_by_step_contraction(
//             &input.iter().map(|i| i.as_slice()).collect::<Vec<&[(Dimension, usize)]>>(),
//             &output_shape,
//             &contraction,
//         );
//         input = step.input_shapes_left;
//         let einsum_step = step.contraction_output;
//         // Need to store the unprocessed inputs in a list somehow which
//         // is going to require first erasing or at least enumerating over
//         // their dimensionality.
//         match einsum_step.len() {
//             0 => unimplemented!(),
//             1 => Einsum::with_1(...),
//             2 => Einsum::with_2(...),
//             3 => Einsum::with_3(...),
//             _ => panic!("Unsupported contraction step, output was larger than supported")
//         }
//     }
//
//     unimplemented!()
// }

// TODO: Once Tensor implementation is working, should be able to actually generalise
// to work on RecordTensor inputs too, they can be passed in up to the .to() step already.
// Final step needs to be aware of some kind of NumericLike type that knows how to lift
// and lower from additional context to a Numeric type for addition and multiplication.
// In some future work can introduce a generic associated type for TensorRef that
// 'knows' what the desired container output is for tensor operations like these to collect
// the results back into, so result type becomes Result<S1::Output<T, O>, InconsistentDimensionLength>
// and somehow we enforce S1::Output == S2::Output????