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
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
//! Crucial structs, enums, functions and types to create computation graphs.
use atomic_refcell::AtomicRefCell;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::ptr;
use std::sync::Arc;
use std::sync::Weak;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::constants::type_size_limit_constants;
use crate::custom_ops::CustomOperation;
use crate::data_types::{get_size_estimation_in_bits, ArrayShape, ScalarType, Type};
use crate::data_values::Value;
use crate::errors::Result;
use crate::type_inference::{create_type_inference_worker, TypeInferenceWorker};

use crate::version::{VersionedData, DATA_VERSION};

#[cfg(feature = "py-binding")]
use crate::custom_ops::PyBindingCustomOperation;
#[cfg(feature = "py-binding")]
use crate::data_types::{PyBindingScalarType, PyBindingType};
#[cfg(feature = "py-binding")]
use crate::typed_value::PyBindingTypedValue;
#[cfg(feature = "py-binding")]
use pywrapper_macro::{enum_to_struct_wrapper, fn_wrapper, impl_wrapper, struct_wrapper};

/// This enum represents different types of slice elements that are used to create indexing slices (see [Slice] and [Graph::get_slice]).
///
/// The semantics is similar to [the NumPy slice indexing](https://numpy.org/doc/stable/user/basics.indexing.html).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "py-binding", enum_to_struct_wrapper)]
pub enum SliceElement {
    /// Single index of a given array dimension.
    ///
    /// The index is given by a signed integer. If negative, the index is interpreted as in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, to choose all the elements of an array with the last index in the first dimension and the first index in the second dimension, one can use a slice `vec![SingleIndex(-1), SingleIndex(0)]`.
    SingleIndex(i64),
    /// Sub-array denotes a range of indices of a given array dimension.
    ///
    /// It follows the description of [the NumPy basic slice](https://numpy.org/doc/stable/user/basics.indexing.html), which is defined by 3 signed integers: `start`, `stop`, `step`. `step` can't be equal to zero.
    ///
    /// For example, to choose all the elements of an array with even indices in the first dimension, one can use a slice `vec![SubArray(Some(0), None, Some(2))].
    SubArray(Option<i64>, Option<i64>, Option<i64>),
    /// Ellipsis denotes several dimensions where indices are not restricted.
    ///
    /// For example, to choose all the elements of an array with index `0` in the first dimension and index `2` in the last dimension, one can use a slice `vec![SingleIndex(0), Ellipsis, SingleIndex(2)]`.
    Ellipsis,
}

/// Slice type denotes an indexing slice (see [NumPy slicing](https://numpy.org/doc/stable/user/basics.indexing.html)).
///
/// It is a vector of slice elements that describes the indices of a sub-array in any appropriate array.
pub type Slice = Vec<SliceElement>;

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Copy)]
#[cfg_attr(feature = "py-binding", enum_to_struct_wrapper)]
pub enum JoinType {
    Inner,
    Left,
    Union,
    Full,
}

#[doc(hidden)]
#[cfg(feature = "py-binding")]
#[pyo3::pymethods]
impl PyBindingJoinType {
    #[staticmethod]
    pub fn from_inner() -> Self {
        PyBindingJoinType {
            inner: JoinType::Inner,
        }
    }
    #[staticmethod]
    pub fn from_left() -> Self {
        PyBindingJoinType {
            inner: JoinType::Left,
        }
    }
    #[staticmethod]
    pub fn from_union() -> Self {
        PyBindingJoinType {
            inner: JoinType::Union,
        }
    }
}

/// Shard config contains the parameters of the Sharding operation, namely:
///
/// - number of shards into which input dataset will be split,
/// - size of each shard, i.e., the number of rows in each shard,
/// - headers of columns whose rows are hashed to find the index of a shard where the corresponding row will be placed.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "py-binding", struct_wrapper)]
pub struct ShardConfig {
    pub num_shards: u64,
    pub shard_size: u64,
    /// headers of columns whose rows are hashed to find the index of a shard where the corresponding row will be placed
    pub shard_headers: Vec<String>,
}

#[doc(hidden)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Operation {
    Input(Type),
    Zeros(Type),
    Ones(Type),
    Add,
    Subtract,
    Multiply,
    // Elementwise multiplication of integer arrays by bit arrays.
    // It leaves an integer array element as is or make it zero it depending on a bit array element.
    MixedMultiply,
    // Dot operation follows the numpy (tensor)dot semantics: https://numpy.org/doc/stable/reference/generated/numpy.dot.html
    Dot,
    // Matmul operation follows the numpy matmul semantics: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
    // In particular, unlike Dot, it doesn't support scalar inputs.
    Matmul,
    Gemm(bool, bool),
    Truncate(u128),
    Sum(ArrayShape),
    CumSum(u64),
    PermuteAxes(ArrayShape),
    Get(ArrayShape),
    GetSlice(Slice),
    Reshape(Type),
    NOP,
    Random(Type),
    PRF(u64, Type),
    PermutationFromPRF(u64, u64),
    Stack(ArrayShape),
    Concatenate(u64),
    Constant(Type, Value),
    A2B,
    B2A(ScalarType),
    CreateTuple,
    CreateNamedTuple(Vec<String>),
    CreateVector(Type),
    TupleGet(u64),
    NamedTupleGet(String),
    VectorGet,
    Zip,
    Repeat(u64),
    Call,
    Iterate,
    ArrayToVector,
    VectorToArray,
    // Operations that can't be compiled to MPC protocols
    RandomPermutation(u64),
    Gather(u64),
    CuckooHash,
    InversePermutation,
    CuckooToPermutation,
    DecomposeSwitchingMap(u64),
    SegmentCumSum,
    Shard(ShardConfig),
    // SQL joins
    Join(JoinType, HashMap<String, String>),
    JoinWithColumnMasks(JoinType, HashMap<String, String>),
    ApplyPermutation(bool),
    Sort(String),
    Custom(CustomOperation),
    // Operations used for debugging graphs.
    Print(String),
    Assert(String),
}

impl fmt::Display for Operation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let operation_name = if let Operation::Custom(custom_op) = self {
            custom_op.get_name()
        } else {
            let operation_w_type_str = format!("{:?}", *self);
            let split_for_operation = operation_w_type_str.split('(');
            let vec_operation_and_types: Vec<&str> = split_for_operation.collect();
            if vec_operation_and_types.is_empty() {
                "-null-".to_owned()
            } else {
                vec_operation_and_types[0].to_owned()
            }
        };
        write!(f, "{operation_name}")
    }
}

impl Operation {
    pub fn is_prf_operation(&self) -> bool {
        matches!(
            self,
            Operation::PRF(_, _) | Operation::PermutationFromPRF(_, _)
        )
    }

    pub fn is_broadcasting_called(&self) -> bool {
        matches!(
            self,
            Operation::Add
                | Operation::Subtract
                | Operation::Multiply
                | Operation::Matmul
                | Operation::Gemm(_, _)
                | Operation::MixedMultiply
                | Operation::Stack(_)
        )
    }

    pub fn is_mpc_compiled(&self) -> bool {
        matches!(
            self,
            Operation::Input(_)
                | Operation::Zeros(_)
                | Operation::Ones(_)
                | Operation::Add
                | Operation::Subtract
                | Operation::Multiply
                | Operation::MixedMultiply
                | Operation::Dot
                | Operation::Matmul
                | Operation::Gemm(_, _)
                | Operation::Truncate(_)
                | Operation::Sum(_)
                | Operation::CumSum(_)
                | Operation::PermuteAxes(_)
                | Operation::Get(_)
                | Operation::GetSlice(_)
                | Operation::Reshape(_)
                | Operation::Stack(_)
                | Operation::Concatenate(_)
                | Operation::Constant(_, _)
                | Operation::A2B
                | Operation::B2A(_)
                | Operation::CreateTuple
                | Operation::CreateNamedTuple(_)
                | Operation::CreateVector(_)
                | Operation::TupleGet(_)
                | Operation::NamedTupleGet(_)
                | Operation::VectorGet
                | Operation::Zip
                | Operation::Repeat(_)
                | Operation::ArrayToVector
                | Operation::VectorToArray
                | Operation::Join(_, _)
                | Operation::JoinWithColumnMasks(_, _)
                | Operation::ApplyPermutation(_)
                | Operation::Sort(_)
        )
    }

    pub fn update_prf_id(&self, prf_id: u64) -> Result<Self> {
        match self {
            Operation::PRF(_, scalar_type) => Ok(Operation::PRF(prf_id, scalar_type.clone())),
            Operation::PermutationFromPRF(_, size) => {
                Ok(Operation::PermutationFromPRF(prf_id, *size))
            }
            _ => Err(runtime_error!("Operation is not a PRF operation")),
        }
    }

    pub fn is_input(&self) -> bool {
        matches!(self, Operation::Input(_))
    }

    pub fn is_const_optimizable(&self) -> Result<bool> {
        match self {
            // Zeros and Ones exist precisely because we don't want to store them as Constants
            // to keep the graph size small.
            Operation::Zeros(_) | Operation::Ones(_) => Ok(false),
            op => Ok(!op.is_input() && !op.is_randomizing()?),
        }
    }

    // If an operation computes a randomized output, return true
    pub fn is_randomizing(&self) -> Result<bool> {
        match self {
            Operation::Random(_)
            | Operation::RandomPermutation(_)
            | Operation::CuckooToPermutation
            | Operation::DecomposeSwitchingMap(_) => Ok(true),
            Operation::Input(_)
            | Operation::Zeros(_)
            | Operation::Ones(_)
            | Operation::A2B
            | Operation::Add
            | Operation::ApplyPermutation(_)
            | Operation::ArrayToVector
            | Operation::Assert(_)
            | Operation::B2A(_)
            | Operation::Subtract
            | Operation::Multiply
            | Operation::MixedMultiply
            | Operation::Matmul
            | Operation::Dot
            | Operation::Gemm(_, _)
            | Operation::Truncate(_)
            | Operation::Sum(_)
            | Operation::CumSum(_)
            | Operation::Concatenate(_)
            | Operation::CreateNamedTuple(_)
            | Operation::CreateTuple
            | Operation::CreateVector(_)
            | Operation::CuckooHash
            | Operation::SegmentCumSum
            | Operation::PermuteAxes(_)
            | Operation::Get(_)
            | Operation::Gather(_)
            | Operation::GetSlice(_)
            | Operation::Reshape(_)
            | Operation::NOP
            | Operation::InversePermutation
            | Operation::PRF(_, _)
            | Operation::PermutationFromPRF(_, _)
            | Operation::Stack(_)
            | Operation::NamedTupleGet(_)
            | Operation::Sort(_)
            | Operation::TupleGet(_)
            | Operation::Constant(_, _)
            | Operation::VectorGet
            | Operation::Zip
            | Operation::Repeat(_)
            | Operation::VectorToArray
            | Operation::Join(_, _)
            | Operation::JoinWithColumnMasks(_, _)
            | Operation::Print(_)
            | Operation::Shard(_) => Ok(false),
            Operation::Call | Operation::Iterate => Err(runtime_error!(
                "The status of operations calling other graphs cannot be defined"
            )),
            Operation::Custom(_) => Err(runtime_error!(
                "The status of custom operations cannot be defined"
            )),
        }
    }
}

struct NodeBody {
    graph: WeakGraph,
    node_dependencies: Vec<WeakNode>,
    graph_dependencies: Vec<WeakGraph>,
    operation: Operation,
    id: u64,
}

#[derive(Serialize, Deserialize)]
struct SerializableNodeBody {
    node_dependencies: Vec<u64>,
    graph_dependencies: Vec<u64>,
    operation: Operation,
}

type NodeBodyPointer = Arc<AtomicRefCell<NodeBody>>;

/// A structure that stores a pointer to a computation graph node that corresponds to an operation.
///
/// [Clone] trait duplicates the pointer, not the underlying nodes.
///
/// [PartialEq] trait compares pointers, not the related nodes.
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// # use ciphercore_base::data_types::{scalar_type, BIT};
/// let c = create_context().unwrap();
/// let g = c.create_graph().unwrap();
/// let t = scalar_type(BIT);
/// let n1 = g.input(t.clone()).unwrap();
/// let n2 = g.input(t).unwrap();
/// assert!(n1 != n2);
/// let n3 = n1.clone();
/// assert!(n1 == n3);
/// ```
#[cfg_attr(feature = "py-binding", struct_wrapper)]
pub struct Node {
    body: NodeBodyPointer,
}

type SerializableNode = Arc<SerializableNodeBody>;

impl Clone for Node {
    /// Returns a new [Node] value with a copy of the pointer to a node.
    fn clone(&self) -> Self {
        Node {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Node {
    /// Tests whether `self` and `other` nodes are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Node] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Node {}

impl Hash for Node {
    /// Hashes the node pointer.
    ///
    /// # Arguments
    ///
    /// `state` - state of a hash function that is changed after hashing the node
    fn hash<H: Hasher>(&self, state: &mut H) {
        ptr::hash(&*self.body, state);
    }
}

/// Public methods which supposed to be imported in Python.
#[cfg_attr(feature = "py-binding", impl_wrapper)]
impl Node {
    /// Returns the parent graph that contains the node.
    ///
    /// # Returns
    ///
    /// Parent graph of the node
    pub fn get_graph(&self) -> Graph {
        self.body.borrow().graph.upgrade()
    }

    /// Returns the dependency nodes that are used to compute the value in the current node.
    ///
    /// # Returns
    ///
    /// Vector of nodes used by the node to perform its operation
    pub fn get_node_dependencies(&self) -> Vec<Node> {
        self.body
            .borrow()
            .node_dependencies
            .iter()
            .map(|n| n.upgrade())
            .collect()
    }

    /// Returns the dependency graphs that are used to compute the value in the current node.
    ///
    /// These dependencies are non-empty only for `Call` and `Iterate` operations.
    ///
    /// # Returns
    ///
    /// Vector of graphs used by the node to perform its operation
    pub fn get_graph_dependencies(&self) -> Vec<Graph> {
        self.body
            .borrow()
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade())
            .collect()
    }

    /// Returns the ID of the node.
    ///
    /// A node ID is a serial number of a node between `0` and `n-1` where `n` is the number of nodes in the parent graph.
    /// This number is equal to the number of nodes in the parent graph before this node was added to it.
    ///
    /// # Returns
    ///
    /// Node ID
    pub fn get_id(&self) -> u64 {
        self.body.borrow().id
    }

    /// Returns the pair of the parent graph ID and node ID
    ///
    /// # Returns
    ///
    /// (Graph ID, Node ID)
    pub fn get_global_id(&self) -> (u64, u64) {
        (self.get_graph().get_id(), self.get_id())
    }

    /// Returns the operation associated with the node.
    ///
    /// # Returns
    ///
    /// Operation associated with the node
    pub fn get_operation(&self) -> Operation {
        self.body.borrow().operation.clone()
    }

    /// Returns the type of the value computed by the node.
    ///
    /// # Returns
    ///
    /// Output type of the node operation
    pub fn get_type(&self) -> Result<Type> {
        let context = self.get_graph().get_context();

        {
            let context_body = context.body.borrow();
            if let Some(tc) = &context_body.type_checker {
                if let Some(cached_type) = tc.cached_node_type(self)? {
                    return Ok(cached_type);
                }
            }
        }

        let mut context_body = context.body.borrow_mut();
        if let Some(tc) = &mut context_body.type_checker {
            tc.process_node(self.clone())
        } else {
            Err(runtime_error!("Type checker is not available"))
        }
    }
    /// Applies [Context::set_node_name] to the parent context and `this` node. Returns the clone of `this`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// ```
    pub fn set_name(&self, name: &str) -> Result<Node> {
        self.get_graph()
            .get_context()
            .set_node_name(self.clone(), name)?;
        Ok(self.clone())
    }

    /// Applies [Context::get_node_name] to the parent context and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// assert_eq!(n.get_name().unwrap(), Some("XOR".to_owned()));
    /// ```
    pub fn get_name(&self) -> Result<Option<String>> {
        self.get_graph().get_context().get_node_name(self.clone())
    }

    /// Adds a node to the parent graph that adds elementwise the array or scalar associated with the node to an array or scalar of the same scalar type associated with another node.
    ///
    /// Applies [Graph::add] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.add(n2).unwrap();
    /// ```
    pub fn add(&self, b: Node) -> Result<Node> {
        self.get_graph().add(self.clone(), b)
    }

    /// Adds a node to the parent graph that subtracts elementwise the array or scalar of the same scalar type associated with another node from an array or scalar associated with the node.
    ///
    /// Applies [Graph::subtract] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.subtract(n2).unwrap();
    /// ```
    pub fn subtract(&self, b: Node) -> Result<Node> {
        self.get_graph().subtract(self.clone(), b)
    }

    /// Adds a node to the parent graph that multiplies elementwise the array or scalar associated with the node by an array or scalar of the same scalar type associated with another node.
    ///
    /// Applies [Graph::multiply] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.multiply(n2).unwrap();
    /// ```
    pub fn multiply(&self, b: Node) -> Result<Node> {
        self.get_graph().multiply(self.clone(), b)
    }

    /// Adds a node to the parent graph that multiplies elementwise the array or scalar associated with the node by a binary array or scalar associated with another node.
    ///
    /// Applies [Graph::mixed_multiply] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(INT32);
    /// let bit_t = scalar_type(BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.input(bit_t).unwrap();
    /// let n3 = n1.mixed_multiply(n2).unwrap();
    /// ```
    pub fn mixed_multiply(&self, b: Node) -> Result<Node> {
        self.get_graph().mixed_multiply(self.clone(), b)
    }

    /// Adds a node to the parent graph that computes the dot product of arrays or scalars associated with the node and another node.
    ///
    /// Applies [Graph::dot] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![10], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.dot(n2).unwrap();
    /// ```
    pub fn dot(&self, b: Node) -> Result<Node> {
        self.get_graph().dot(self.clone(), b)
    }

    /// Adds a node to the parent graph that computes the matrix product of two arrays associated with the node and another node.
    ///
    /// Applies [Graph::matmul] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = n1.matmul(n2).unwrap();
    /// ```
    pub fn matmul(&self, b: Node) -> Result<Node> {
        self.get_graph().matmul(self.clone(), b)
    }

    /// Adds a node to the parent graph that computes the generatl matrix product of two arrays associated with the node and another node.
    ///
    /// Applies [Graph::gemm] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = n1.gemm(n2, false, true).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn gemm(&self, b: Node, transpose_a: bool, transpose_b: bool) -> Result<Node> {
        self.get_graph()
            .gemm(self.clone(), b, transpose_a, transpose_b)
    }

    /// Adds a node that computes a join of a given type on two named tuples along given key headers.
    /// More detailed documentation can be found in [Graph::join].
    ///
    /// Applies [Graph::join] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, JoinType};
    /// # use ciphercore_base::data_types::{INT32, INT64, UINT8, BIT, array_type, named_tuple_type};
    /// # use ciphercore_base::type_inference::NULL_HEADER;
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1n = array_type(vec![100], BIT);
    /// let t11 = array_type(vec![100], INT32);
    /// let t12 = array_type(vec![100, 128], BIT);
    /// let t13 = array_type(vec![100], INT64);
    /// let t2n = array_type(vec![50], BIT);
    /// let t21 = array_type(vec![50], INT32);
    /// let t22 = array_type(vec![50, 128], BIT);
    /// let t23 = array_type(vec![50], UINT8);
    /// let t1 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t1n),
    ///     ("ID".to_owned(), t11),
    ///     ("Occupation".to_owned(), t12),
    ///     ("Revenue".to_owned(), t13),
    /// ]);
    /// let t2 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t2n),
    ///     ("ID".to_owned(), t21),
    ///     ("Job".to_owned(), t22),
    ///     ("Age".to_owned(), t23),
    /// ]);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = n1.join(n2, JoinType::Inner, HashMap::from([
    ///     ("ID".to_owned(), "ID".to_owned()),
    ///     ("Occupation".to_owned(), "Job".to_owned()),
    /// ])).unwrap();
    /// ```
    pub fn join(&self, b: Node, t: JoinType, headers: HashMap<String, String>) -> Result<Node> {
        self.get_graph().join(self.clone(), b, t, headers)
    }

    /// Adds a node that computes a join of a given type on two named tuples along given key headers.
    /// More detailed documentation can be found in [Graph::join_with_column_masks].
    ///
    /// Applies [Graph::join_with_column_masks] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, JoinType};
    /// # use ciphercore_base::data_types::{INT32, INT64, UINT8, BIT, array_type, named_tuple_type, tuple_type};
    /// # use ciphercore_base::type_inference::NULL_HEADER;
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1n = array_type(vec![100], BIT);
    /// let t11 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100], INT32)]);
    /// let t12 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100, 128], BIT)]);
    /// let t13 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100], INT64)]);
    /// let t2n = array_type(vec![50], BIT);
    /// let t21 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50], INT32)]);
    /// let t22 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50, 128], BIT)]);
    /// let t23 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50], UINT8)]);
    /// let t1 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t1n),
    ///     ("ID".to_owned(), t11),
    ///     ("Occupation".to_owned(), t12),
    ///     ("Revenue".to_owned(), t13),
    /// ]);
    /// let t2 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t2n),
    ///     ("ID".to_owned(), t21),
    ///     ("Job".to_owned(), t22),
    ///     ("Age".to_owned(), t23),
    /// ]);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = n1.join_with_column_masks(n2, JoinType::Inner, HashMap::from([
    ///     ("ID".to_owned(), "ID".to_owned()),
    ///     ("Occupation".to_owned(), "Job".to_owned()),
    /// ])).unwrap();
    /// ```
    pub fn join_with_column_masks(
        &self,
        b: Node,
        t: JoinType,
        headers: HashMap<String, String>,
    ) -> Result<Node> {
        self.get_graph()
            .join_with_column_masks(self.clone(), b, t, headers)
    }

    /// Adds a node that applies a permutation to the array along the first dimension.
    ///
    /// # Arguments
    ///
    /// * `p` - node containing a permutation.
    ///
    /// # Returns
    ///
    /// New permuted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, UINT64, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![25, 3], INT32);
    /// let a = g.input(t).unwrap();
    /// let p = g.input(array_type(vec![25], UINT64)).unwrap();
    /// let a = a.apply_permutation(p).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn apply_permutation(&self, p: Node) -> Result<Node> {
        self.get_graph().apply_permutation(self.clone(), p)
    }

    /// Adds a node that applies an inverse permutation to the array along the first dimension.
    ///
    /// # Arguments
    ///
    /// * `p` - node containing a permutation.
    ///
    /// # Returns
    ///
    /// New permuted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, UINT64, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![25, 3], INT32);
    /// let a = g.input(t).unwrap();
    /// let p = g.input(array_type(vec![25], UINT64)).unwrap();
    /// let a = a.apply_inverse_permutation(p).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn apply_inverse_permutation(&self, p: Node) -> Result<Node> {
        self.get_graph().apply_inverse_permutation(self.clone(), p)
    }

    /// Adds a node that sorts a table given as named tuple according to the column given by the key argument.
    /// The key column must be a 2-d BIT array of shape [n, b], interpreted as bitstrings of length b.
    /// Other columns in the named tuple must be arrays of arbitrary type and shape, as long as they
    /// share the first dimension: [n, ...].
    /// Bitstrings are sorted lexicographically, and the sorting algorithm is stable: preserving relative
    /// order of entries in other arrays where the corresponding key entries match.
    ///
    /// # Arguments
    /// * `key` - name of the field to sort on it, this array must be 2-d of type BIT.
    ///
    /// # Returns
    ///
    /// New sorted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, UINT64, array_type, named_tuple_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let v1 = g.input(array_type(vec![20], INT32)).unwrap();
    /// let v2 = g.input(array_type(vec![20, 10, 2], UINT64)).unwrap();
    /// let k = g.input(array_type(vec![20, 32], BIT)).unwrap();
    /// let a = g.create_named_tuple(vec![("key".to_string(), k), ("value1".to_string(), v1), ("value2".to_string(), v2)]).unwrap();
    /// let a = a.sort("key".to_string()).unwrap();
    /// ```
    pub fn sort(&self, key: String) -> Result<Node> {
        self.get_graph().sort(self.clone(), key)
    }

    /// Adds a node to the parent graph that divides a scalar or each entry of the array associated with the node by a positive constant integer `scale`.
    ///
    /// Applies [Graph::add] to the parent graph, `this` node and `scale`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.truncate(4).unwrap();
    /// ```
    pub fn truncate(&self, scale: u128) -> Result<Node> {
        self.get_graph().truncate(self.clone(), scale)
    }

    /// Adds a node to the parent graph that computes the sum of entries of the array associated with the node along given axes.
    ///
    /// Applies [Graph::sum] to the parent graph, `this` node and `axes`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.sum(axes).unwrap();
    /// ```
    pub fn sum(&self, axes: ArrayShape) -> Result<Node> {
        self.get_graph().sum(self.clone(), axes)
    }

    /// Adds a node to the parent graph that computes the cumulative sum of elements along a given axis.
    ///
    /// Applies [Graph::cum_sum] to the parent graph, `this` node and `axis`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.cum_sum(1).unwrap();
    /// ```
    pub fn cum_sum(&self, axis: u64) -> Result<Node> {
        self.get_graph().cum_sum(self.clone(), axis)
    }

    /// Adds a node to the parent graph that permutes the array associated with the node along given axes.
    ///
    /// Applies [Graph::permute_axes] to the parent graph, `this` node and `axes`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0, 2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.permute_axes(axes).unwrap();
    /// ```
    pub fn permute_axes(&self, axes: ArrayShape) -> Result<Node> {
        self.get_graph().permute_axes(self.clone(), axes)
    }

    /// Adds a node to the parent graph that inverts a given permutation.
    ///
    /// Applies [Graph::inverse_permutation] to the parent graph and `this` node.
    #[doc(hidden)]
    pub fn inverse_permutation(&self) -> Result<Node> {
        self.get_graph().inverse_permutation(self.clone())
    }

    /// Adds a node to the parent graph that extracts a sub-array with a given index from the array associated with the node.
    ///
    /// Applies [Graph::get] to the parent graph, `this` node and `index`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let index = vec![2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.get(index).unwrap();
    /// ```
    pub fn get(&self, index: ArrayShape) -> Result<Node> {
        self.get_graph().get(self.clone(), index)
    }

    /// Adds a node that extracts a sub-array corresponding to a given slice from the array associated with the node.
    ///
    /// Applies [Graph::get_slice] to the parent graph, `this` node and `slice`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, SliceElement};
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let slice = vec![SliceElement::Ellipsis, SliceElement::SubArray(None, None, Some(-2))];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.get_slice(slice).unwrap();
    /// ```
    pub fn get_slice(&self, slice: Slice) -> Result<Node> {
        self.get_graph().get_slice(self.clone(), slice)
    }

    /// Adds a node to the parent graph that reshapes a value associated with the node to a given compatible type.
    ///
    /// Applies [Graph::reshape] to the parent graph, `this` node and `new_type`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let old_t = array_type(vec![3, 2, 3], INT32);
    /// let new_t = array_type(vec![3,6], INT32);
    /// let n1 = g.input(old_t).unwrap();
    /// let n2 = n1.reshape(new_t).unwrap();
    /// ```
    pub fn reshape(&self, new_type: Type) -> Result<Node> {
        self.get_graph().reshape(self.clone(), new_type)
    }

    #[doc(hidden)]
    pub fn nop(&self) -> Result<Node> {
        self.get_graph().nop(self.clone())
    }

    #[doc(hidden)]
    pub fn prf(&self, iv: u64, output_type: Type) -> Result<Node> {
        self.get_graph().prf(self.clone(), iv, output_type)
    }

    #[doc(hidden)]
    pub fn permutation_from_prf(&self, iv: u64, n: u64) -> Result<Node> {
        self.get_graph().permutation_from_prf(self.clone(), iv, n)
    }

    /// Adds a node to the parent graph converting an integer array or scalar associated with the node to the binary form.
    ///
    /// Applies [Graph::a2b] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.a2b().unwrap();
    /// ```
    pub fn a2b(&self) -> Result<Node> {
        self.get_graph().a2b(self.clone())
    }

    /// Adds a node to the parent graph converting a binary array associated with the node to an array of a given scalar type.
    ///
    /// Applies [Graph::b2a] to the parent graph, `this` node and `scalar_type`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 32], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.b2a(INT32).unwrap();
    /// ```
    pub fn b2a(&self, scalar_type: ScalarType) -> Result<Node> {
        self.get_graph().b2a(self.clone(), scalar_type)
    }

    /// Adds a node that extracts an element of a tuple associated with the node.
    ///
    /// Applies [Graph::tuple_get] to the parent graph, `this` node and `index`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1, n2]).unwrap();
    /// let n4 = n3.tuple_get(1).unwrap();
    /// ```
    pub fn tuple_get(&self, index: u64) -> Result<Node> {
        self.get_graph().tuple_get(self.clone(), index)
    }

    /// Adds a node to the parent graph that extracts an element of a named tuple associated with the node.
    ///
    /// Applies [Graph::named_tuple_get] to the parent graph, `this` node and the `key` string.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// let n4 = n3.named_tuple_get("node2".to_owned()).unwrap();
    /// ```
    pub fn named_tuple_get(&self, key: String) -> Result<Node> {
        self.get_graph().named_tuple_get(self.clone(), key)
    }

    /// Adds a node to the parent graph that extracts an element of a vector associated with the node.
    ///
    /// Applies [Graph::vector_get] to the parent graph, `this` node and the `index` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT32, INT32, array_type, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n4 = n3.vector_get(index).unwrap();
    /// ```
    pub fn vector_get(&self, index: Node) -> Result<Node> {
        self.get_graph().vector_get(self.clone(), index)
    }

    /// Adds a node to the parent graph converting an array associated with the node to a vector.
    ///
    /// Applies [Graph::array_to_vector] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, scalar_type, INT32, UINT32};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![4, 3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.array_to_vector(n1).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n3 = n2.vector_get(index).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_vector());
    /// assert_eq!(n3.get_type().unwrap().get_shape(), vec![3,2]);
    /// ```
    pub fn array_to_vector(&self) -> Result<Node> {
        self.get_graph().array_to_vector(self.clone())
    }

    /// Adds a node to the parent graph converting a vector associated with the node to an array.
    ///
    /// Applies [Graph::vector_to_array] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = n1.vector_to_array().unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_array());
    /// assert_eq!(n2.get_type().unwrap().get_shape(), vec![4, 3, 2]);
    /// ```
    pub fn vector_to_array(&self) -> Result<Node> {
        self.get_graph().vector_to_array(self.clone())
    }

    /// Adds a node to the parent graph converting a vector associated with the node to an array.
    ///
    /// Applies [Graph::gather] to the parent graph and `this` node.
    pub fn gather(&self, indices: Node, axis: u64) -> Result<Node> {
        self.get_graph().gather(self.clone(), indices, axis)
    }

    /// Adds a node that creates a vector with `n` copies of a value of this node.
    ///
    /// Applies [Graph::repeat] to the parent graph, `this` node and `n`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.repeat(10).unwrap();
    /// ```
    pub fn repeat(&self, n: u64) -> Result<Node> {
        self.get_graph().repeat(self.clone(), n)
    }

    /// Adds a node returning the Cuckoo hash map of an input array of binary strings using provided hash functions.
    ///
    /// Applies [Graph::cuckoo_hash] to the parent graph, `this` node and `hash_matrices`.
    #[doc(hidden)]
    pub fn cuckoo_hash(&self, hash_matrices: Node) -> Result<Node> {
        self.get_graph().cuckoo_hash(self.clone(), hash_matrices)
    }

    /// Adds a node that, given an input multidimensional array A, binary one-dimensional array B (first dimension is n in both array) and starting value v, computes the following iteration
    ///
    /// output[i] = A[i-1] + B[i-1] * output[i-1]
    ///
    /// where i in {1,...,n} and output[0] = v.
    ///
    /// Applies [Graph::segment_cumsum] to the parent graph, `this` node, `binary_array` and `first_row`.
    #[doc(hidden)]
    pub fn segment_cumsum(&self, binary_array: Node, first_row: Node) -> Result<Node> {
        self.get_graph()
            .segment_cumsum(self.clone(), binary_array, first_row)
    }

    /// Adds a node that computes sharding of a given table according to a given sharding config.
    /// Sharding config contains names of the columns whose hashed values are used for sharding.
    ///
    /// Each shard is accompanied by a Boolean mask indicating whether a corresponding row stems from the input table or padded (1 if a row comes from input).
    ///
    /// Applies [Graph::shard] to the parent graph, `this` node and `shard_config`.
    #[doc(hidden)]
    pub fn shard(&self, shard_config: ShardConfig) -> Result<Node> {
        self.get_graph().shard(self.clone(), shard_config)
    }

    /// Adds a node that converts a switching map array into a tuple of the following components:
    /// - a permutation map array with deletion,
    /// - a duplication map array,
    /// - a permutation map array without deletion.
    ///
    /// The composition of these maps is equal to the input switching map, which is an array containing non-unique indices of some array.
    ///
    /// Applies [Graph::decompose_switching_map] to the parent graph and `this`.
    #[doc(hidden)]
    pub fn decompose_switching_map(&self, n: u64) -> Result<Node> {
        self.get_graph().decompose_switching_map(self.clone(), n)
    }

    /// Adds a node that converts a Cuckoo hash table to a random permutation.
    ///
    /// Applies [Graph::cuckoo_to_permutation] to the parent graph and `this` node.
    #[doc(hidden)]
    pub fn cuckoo_to_permutation(&self) -> Result<Node> {
        self.get_graph().cuckoo_to_permutation(self.clone())
    }

    /// Adds an operation which logs the value of the node at runtime.
    pub fn print(&self, message: String) -> Result<Node> {
        self.get_graph().print(message, self.clone())
    }

    /// Applies [Graph::set_output_node] to the parent graph and `this` node.
    ///
    /// # Returns
    ///
    /// This node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn set_as_output(&self) -> Result<Node> {
        self.get_graph().set_output_node(self.clone())?;
        Ok(self.clone())
    }
}

/// Methods which aren't supposed to be imported in Python.
impl Node {
    fn make_serializable(&self) -> SerializableNode {
        Arc::new(SerializableNodeBody {
            node_dependencies: self
                .get_node_dependencies()
                .iter()
                .map(|n| n.get_id())
                .collect(),
            graph_dependencies: self
                .get_graph_dependencies()
                .iter()
                .map(|n| n.get_id())
                .collect(),
            operation: self.get_operation(),
        })
    }

    fn downgrade(&self) -> WeakNode {
        WeakNode {
            body: Arc::downgrade(&self.body),
        }
    }

    #[doc(hidden)]
    pub fn add_annotation(&self, annotation: NodeAnnotation) -> Result<Node> {
        self.get_graph()
            .get_context()
            .add_node_annotation(self, annotation)?;
        Ok(self.clone())
    }

    #[doc(hidden)]
    pub fn get_annotations(&self) -> Result<Vec<NodeAnnotation>> {
        self.get_graph()
            .get_context()
            .get_node_annotations(self.clone())
    }
}
type WeakNodeBodyPointer = Weak<AtomicRefCell<NodeBody>>;

struct WeakNode {
    body: WeakNodeBodyPointer,
}

impl WeakNode {
    //upgrade function panics if the the Node pointer it downgraded from went out of scope
    fn upgrade(&self) -> Node {
        Node {
            body: self.body.upgrade().unwrap(),
        }
    }
}

impl Clone for WeakNode {
    fn clone(&self) -> Self {
        WeakNode {
            body: self.body.clone(),
        }
    }
}

struct GraphBody {
    finalized: bool,
    nodes: Vec<Node>,
    output_node: Option<WeakNode>,
    id: u64,
    context: WeakContext,
}

#[derive(Serialize, Deserialize)]
struct SerializableGraphBody {
    finalized: bool,
    nodes: Vec<SerializableNode>,
    output_node: Option<u64>,
}

type GraphBodyPointer = Arc<AtomicRefCell<GraphBody>>;

/// A structure that stores a pointer to a computation graph, where every node corresponds to an operation.
///
/// # Rust crates
///
/// [Clone] trait duplicates the pointer, not the underlying graph.
///
/// [PartialEq] trait compares pointers, not the related graphs.
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// let c = create_context().unwrap();
/// let g1 = c.create_graph().unwrap();
/// let g2 = c.create_graph().unwrap();
/// assert_ne!(g1, g2);
/// let g3 = g1.clone();
/// assert_eq!(g1, g3);
/// ```
#[cfg_attr(feature = "py-binding", struct_wrapper)]
pub struct Graph {
    body: GraphBodyPointer,
}

type SerializableGraph = Arc<SerializableGraphBody>;

impl fmt::Debug for Graph {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Graph")
            .field("body", &self.body.as_ptr())
            .finish()
    }
}

impl Clone for Graph {
    /// Returns a new [Graph] value with a copy of the pointer to a computation graph.
    fn clone(&self) -> Self {
        Graph {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Graph {
    /// Tests whether `self` and `other` graphs are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Graph] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Graph {}

impl Hash for Graph {
    /// Hashes the graph pointer.
    ///
    /// # Arguments
    ///
    /// `state` - state of a hash function that is changed after hashing the graph
    fn hash<H: Hasher>(&self, state: &mut H) {
        ptr::hash(&*self.body, state);
    }
}

/// Public methods which supposed to be imported in Python.
#[cfg_attr(feature = "py-binding", impl_wrapper)]
impl Graph {
    /// Applies [Context::set_main_graph] to the parent context and `this` graph. Returns the clone of `this`.
    ///
    /// # Returns
    ///
    /// This graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n = g.input(t).unwrap();
    /// n.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// g.set_as_main().unwrap();
    /// ```
    pub fn set_as_main(&self) -> Result<Graph> {
        self.get_context().set_main_graph(self.clone())?;
        Ok(self.clone())
    }

    /// Applies [Context::set_graph_name] to the parent context and `this` graph. Returns the clone of `this`.
    ///
    /// # Arguments
    ///
    /// `name` - name of the graph
    ///
    /// # Returns
    ///
    /// This graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// ```
    pub fn set_name(&self, name: &str) -> Result<Graph> {
        self.get_context().set_graph_name(self.clone(), name)?;
        Ok(self.clone())
    }

    /// Applies [Context::get_graph_name] to the parent context and `this` graph.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// assert_eq!(g.get_name().unwrap(), "relu".to_owned());
    /// ```
    pub fn get_name(&self) -> Result<String> {
        self.get_context().get_graph_name(self.clone())
    }

    /// Applies [Context::retrieve_node] to the parent context and `this` graph.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// n.set_name("input_node").unwrap();
    /// assert!(n == g.retrieve_node("input_node").unwrap());
    /// ```
    pub fn retrieve_node(&self, name: &str) -> Result<Node> {
        self.get_context().retrieve_node(self.clone(), name)
    }

    /// Adds an input node to the graph and returns it.
    ///
    /// During evaluation, input nodes require values to be supplied.
    ///
    /// # Arguments
    ///
    /// `input_type` - type of a new input node
    ///
    /// # Returns
    ///
    /// New input node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// ```
    pub fn input(&self, input_type: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Input(input_type))
    }

    /// Adds an node with zeros of given type.
    ///
    /// Compared to `constant` this node does produce a big value array in serialized graph.
    ///
    /// # Arguments
    ///
    /// `t` - node type
    ///
    /// # Returns
    ///
    /// New node with zeros of given type.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT8, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let z = g.zeros(array_type(vec![10, 20], UINT8)).unwrap();
    /// ```
    pub fn zeros(&self, t: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Zeros(t))
    }

    /// Adds an node with ones of given type.
    ///
    /// Compared to `constant` this node does produce a big value array in serialized graph.
    ///
    /// # Arguments
    ///
    /// `t` - node type
    ///
    /// # Returns
    ///
    /// New node with ones of given type.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT8, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let z = g.ones(array_type(vec![10, 20], UINT8)).unwrap();
    /// ```
    pub fn ones(&self, t: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Ones(t))
    }

    /// Adds a node that sums two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, adding two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first term (array or scalar)
    /// * `b` - node containing the second term (array or scalar)
    ///
    /// # Returns
    ///
    /// New addition node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.add(n1, n2).unwrap();
    /// ```
    pub fn add(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Add)
    }

    /// Adds a node that subtracts two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, subtracting two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the minuend (array or scalar)
    /// * `b` - node containing the subtrahend (array or scalar)
    ///
    /// # Returns
    ///
    /// New subtraction node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.subtract(n1, n2).unwrap();
    /// ```
    pub fn subtract(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Subtract)
    }

    /// Adds a node that multiplies two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, multiplication of two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first factor (array or scalar)
    /// * `b` - node containing the second factor (array or scalar)
    ///
    /// # Returns
    ///
    /// New multiplication node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.multiply(n1, n2).unwrap();
    /// ```
    pub fn multiply(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Multiply)
    }

    /// Adds a node that multiplies an integer array or scalar by a binary array or scalar elementwise.
    /// For each integer element, this operation returns this element or zero depending on the corresponding bit element.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, multiplication of two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an integer array or scalar
    /// * `b` - node containing a binary array or scalar
    ///
    /// # Returns
    ///
    /// New mixed multiplication node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = scalar_type(INT32);
    /// let t2 = scalar_type(BIT);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.mixed_multiply(n1, n2).unwrap();
    /// ```
    pub fn mixed_multiply(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::MixedMultiply)
    }

    /// Adds a node that computes the dot product according to [the NumPy rules](https://numpy.org/doc/stable/reference/generated/numpy.dot.html):
    /// * if both factors are 1-dimensional arrays, return their inner product;
    /// * if both factors are 2-dimensional arrays, return their matrix product;
    /// * if one of the factors is scalar, return the result of [multiply](Graph::multiply);
    /// * if the first factor is n-dimensional and the second one is 1-dimensional,
    /// compute the elementwise multiplication and return the sum over the last axis.
    /// * if both factors are n-dimensional (n>2), return the sum product
    /// over the last axis of the first factor and the second-to-last axis of the second factor, i.e.
    ///
    /// `dot(A, B)[i,j,k,m] = sum(A[i,j,:] * B[k,:,m])` (in the NumPy notation).
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first factor (array or scalar)
    /// * `b` - node containing the second factor (array or scalar)
    ///
    /// # Returns
    ///
    /// New dot product node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![10], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.dot(n1, n2).unwrap();
    /// ```
    pub fn dot(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Dot)
    }

    /// Adds a node that computes the matrix product of two arrays according to [the NumPy rules](https://numpy.org/doc/stable/reference/generated/numpy.matmul.html).
    ///
    /// Each array is represented as an array of 2-dimensional matrix elements and this node returns the elementwise product of such matrix arrays.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first array
    /// * `b` - node containing the second array
    ///
    /// # Returns
    ///
    /// New matrix product node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.matmul(n1, n2).unwrap();
    /// ```
    pub fn matmul(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Matmul)
    }

    /// Adds a node that computes the general matrix product of two arrays according to [the ONNX rules](https://github.com/onnx/onnx/blob/main/docs/Operators.md#Gemm) with `alpha = 1`, `beta = 0` and `C = 0`.
    ///
    /// Each array is represented as an array of 2-dimensional matrix elements and this node returns the elementwise product of such matrix arrays.
    /// Each matrix should have at least 2 dimensions.
    /// To multiply by 1-dimensional matrices (i.e., vectors), please resort to `matmul` or `dot`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first array
    /// * `b` - node containing the second array
    /// * `transpose_a` - if true, the first array will be transposed
    /// * `transpose_b` - if true, the second array will be transposed
    ///
    /// # Returns
    ///
    /// New Gemm node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.gemm(n1, n2, false, true).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn gemm(&self, a: Node, b: Node, transpose_a: bool, transpose_b: bool) -> Result<Node> {
        self.add_node(
            vec![a, b],
            vec![],
            Operation::Gemm(transpose_a, transpose_b),
        )
    }

    /// Adds a node that computes a join of a given type on two named tuples along given key headers.
    ///
    /// Each tuple should consist of arrays having the same number of rows, i.e. the first dimensions of these arrays should be equal.
    ///
    /// In addition, each named tuple should have a binary array named with NULL_HEADER that contains zeros in rows void of content; otherwise, it contains ones.
    /// This column is called the null column.
    ///
    /// Let `row key` be the bitstring obtained by concatenating data elements for given key headers.
    /// **WARNING**: Rows must have unique row keys, except for rows where NULL_HEADER is zero: those rows are ignored.
    ///
    /// This operation returns:
    /// - Inner join: a named tuple containing rows where input tuples have matching row keys.
    /// - Left join: a named tuple containing all the rows of the first input tuple merged with the rows of the second input tuple having same row keys.
    /// - Union join: a named tuple containing rows of the first input tuple that are not in the inner join and all the rows of the second tuple.
    /// In contrast to the SQL union, this operation does not require that input datasets have respective columns of the same type.
    /// This means that columns of both datasets are included and filled with zeros where no data can be retrieved.
    /// Namely, the rows of the second set in the union join will contain zeros in non-key columns of the first set and vice versa.
    /// - Full join: a named tuple containing all the rows of input tuples.
    /// If the row key of a row of the first set match with the row key of a row of the second set, they are merged into one.
    /// The order of rows goes as follows:
    /// 1. the rows of the first set that don't belong to the inner join.
    /// 2. all the rows of the second set including those merged with the rows of the first set as in inner join.
    /// In this form, full join is computed as `union_join(a, left_join(b, a))`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first named tuple
    /// * `b` - node containing the second named tuple
    /// * `t` - join type (Inner/Left/Union/Full)
    /// * `headers` - headers of columns along which the join is performed
    ///
    /// # Returns
    ///
    /// New join node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, JoinType};
    /// # use ciphercore_base::data_types::{INT32, INT64, UINT8, BIT, array_type, named_tuple_type};
    /// # use ciphercore_base::type_inference::NULL_HEADER;
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1n = array_type(vec![100], BIT);
    /// let t11 = array_type(vec![100], INT32);
    /// let t12 = array_type(vec![100, 128], BIT);
    /// let t13 = array_type(vec![100], INT64);
    /// let t2n = array_type(vec![50], BIT);
    /// let t21 = array_type(vec![50], INT32);
    /// let t22 = array_type(vec![50, 128], BIT);
    /// let t23 = array_type(vec![50], UINT8);
    /// let t1 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t1n),
    ///     ("ID".to_owned(), t11),
    ///     ("Occupation".to_owned(), t12),
    ///     ("Revenue".to_owned(), t13),
    /// ]);
    /// let t2 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t2n),
    ///     ("ID".to_owned(), t21),
    ///     ("Job".to_owned(), t22),
    ///     ("Age".to_owned(), t23),
    /// ]);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.join(n1, n2, JoinType::Inner, HashMap::from([
    ///     ("ID".to_owned(), "ID".to_owned()),
    ///     ("Occupation".to_owned(), "Job".to_owned()),
    /// ])).unwrap();
    /// ```
    pub fn join(
        &self,
        a: Node,
        b: Node,
        t: JoinType,
        headers: HashMap<String, String>,
    ) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Join(t, headers))
    }

    /// Adds a node that computes a join of a given type on two named tuples along given key headers.
    ///
    /// Each tuple should consist of pairs of arrays having the same number of rows, i.e. the first dimensions of these arrays should be equal.
    /// Each pair has a binary array that contains zeros in rows where the data array has no content and an array with data.
    ///
    /// In addition, each named tuple should have a binary array named with NULL_HEADER that contains zeros in rows void of content; otherwise, it contains ones.
    /// This column is called the null column.
    ///
    /// Let `row key` be the bitstring obtained by concatenating data elements for given key headers where all the corresponding mask elements are set to one.
    /// **WARNING**: Rows must have unique row keys, except for rows where NULL_HEADER is zero or at least one mask element in given key headers is zero.
    /// Rows with zero NULL_HEADER are ignored.
    /// We assume that rows with zero mask elements don't match with other rows.
    /// Thus, they can't show up in inner and left joins, but can be copied over to the result of union or full joins.
    ///
    /// This operation returns:
    /// - Inner join: a named tuple containing rows where input tuples have matching row keys.
    /// - Left join: a named tuple containing all the rows of the first input tuple merged with the rows of the second input tuple having same row keys.
    /// - Union join: a named tuple containing rows of the first input tuple that are not in the inner join and all the rows of the second tuple.
    /// In contrast to the SQL union, this operation does not require that input datasets have respective columns of the same type.
    /// This means that columns of both datasets are included and filled with zeros where no data can be retrieved.
    /// Namely, the rows of the second set in the union join will contain zeros in non-key columns of the first set and vice versa.
    /// - Full join: a named tuple containing all the rows of input tuples.
    /// If the row key of a row of the first set match with the row key of a row of the second set, they are merged into one.
    /// The order of rows goes as follows:
    /// 1. the rows of the first set that don't belong to the inner join.
    /// 2. all the rows of the second set including those merged with the rows of the first set as in inner join.
    /// In this form, full join is computed as `union_join(a, left_join(b, a))`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first named tuple
    /// * `b` - node containing the second named tuple
    /// * `t` - join type (Inner/Left/Union/Full)
    /// * `headers` - headers of columns along which the join is performed
    ///
    /// # Returns
    ///
    /// New join node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, JoinType};
    /// # use ciphercore_base::data_types::{INT32, INT64, UINT8, BIT, array_type, named_tuple_type, tuple_type};
    /// # use ciphercore_base::type_inference::NULL_HEADER;
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1n = array_type(vec![100], BIT);
    /// let t11 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100], INT32)]);
    /// let t12 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100, 128], BIT)]);
    /// let t13 = tuple_type(vec![array_type(vec![100], BIT), array_type(vec![100], INT64)]);
    /// let t2n = array_type(vec![50], BIT);
    /// let t21 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50], INT32)]);
    /// let t22 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50, 128], BIT)]);
    /// let t23 = tuple_type(vec![array_type(vec![50], BIT), array_type(vec![50], UINT8)]);
    /// let t1 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t1n),
    ///     ("ID".to_owned(), t11),
    ///     ("Occupation".to_owned(), t12),
    ///     ("Revenue".to_owned(), t13),
    /// ]);
    /// let t2 = named_tuple_type(vec![
    ///     (NULL_HEADER.to_owned(), t2n),
    ///     ("ID".to_owned(), t21),
    ///     ("Job".to_owned(), t22),
    ///     ("Age".to_owned(), t23),
    /// ]);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.join_with_column_masks(n1, n2, JoinType::Inner, HashMap::from([
    ///     ("ID".to_owned(), "ID".to_owned()),
    ///     ("Occupation".to_owned(), "Job".to_owned()),
    /// ])).unwrap();
    /// ```
    pub fn join_with_column_masks(
        &self,
        a: Node,
        b: Node,
        t: JoinType,
        headers: HashMap<String, String>,
    ) -> Result<Node> {
        self.add_node(
            vec![a, b],
            vec![],
            Operation::JoinWithColumnMasks(t, headers),
        )
    }

    /// Adds a node that applies a permutation to the array along the first dimension.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array to permute.
    /// * `p` - node containing a permutation.
    ///
    /// # Returns
    ///
    /// New permuted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, UINT64, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![25, 3], INT32);
    /// let a = g.input(t).unwrap();
    /// let p = g.input(array_type(vec![25], UINT64)).unwrap();
    /// let a = g.apply_permutation(a, p).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn apply_permutation(&self, a: Node, p: Node) -> Result<Node> {
        self.add_node(vec![a, p], vec![], Operation::ApplyPermutation(false))
    }

    /// Adds a node that applies an inverse permutation to the array along the first dimension.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array to permute.
    /// * `p` - node containing a permutation.
    ///
    /// # Returns
    ///
    /// New permuted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, UINT64, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![25, 3], INT32);
    /// let a = g.input(t).unwrap();
    /// let p = g.input(array_type(vec![25], UINT64)).unwrap();
    /// let a = g.apply_inverse_permutation(a, p).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn apply_inverse_permutation(&self, a: Node, p: Node) -> Result<Node> {
        self.add_node(vec![a, p], vec![], Operation::ApplyPermutation(true))
    }

    /// Adds a node that sorts a table given as named tuple according to the column given by the key argument.
    /// The key column must be a 2-d BIT array of shape [n, b], interpreted as bitstrings of length b.
    /// Other columns in the named tuple must be arrays of arbitrary type and shape, as long as they
    /// share the first dimension: [n, ...].
    /// Bitstrings are sorted lexicographically, and the sorting algorithm is stable: preserving relative
    /// order of entries in other arrays where the corresponding key entries match.
    ///
    /// # Arguments
    /// * `a` - node containing a named tuple -- arrays to sort.
    /// * `key` - name of the field to sort on it, this array must be 2-d of type BIT.
    ///
    /// # Returns
    ///
    /// New sorted node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, UINT64, array_type, named_tuple_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let v1 = g.input(array_type(vec![20], INT32)).unwrap();
    /// let v2 = g.input(array_type(vec![20, 10, 2], UINT64)).unwrap();
    /// let k = g.input(array_type(vec![20, 32], BIT)).unwrap();
    /// let a = g.create_named_tuple(vec![("key".to_string(), k), ("value1".to_string(), v1), ("value2".to_string(), v2)]).unwrap();
    /// let a = g.sort(a, "key".to_string()).unwrap();
    /// ```
    pub fn sort(&self, a: Node, key: String) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Sort(key))
    }

    /// Adds a node that divides a scalar or each entry of an array by a positive constant integer `scale`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a scalar or an array
    /// * `scale` - positive integer
    ///
    /// # Returns
    ///
    /// New truncate node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.truncate(n1, 4).unwrap();
    /// ```
    pub fn truncate(&self, a: Node, scale: u128) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Truncate(scale))
    }

    /// Adds a node that computes the sum of entries of an array along given axes (see [numpy.sum](https://numpy.org/doc/stable/reference/generated/numpy.sum.html)).
    ///
    /// For example, summing the array `[[1000, 200], [30, 4]]` along the first or the second axes results in the arrays `[1030,204]` or `[1200,34]`, respectively. Summing along both axes yields `1234`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `axes` - indices of the axes of `a`
    ///
    /// # Returns
    ///
    /// New sum node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.sum(n1, axes).unwrap();
    /// ```
    pub fn sum(&self, a: Node, axes: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Sum(axes))
    }

    /// Adds a node that computes the cumulative sum of elements along a given axis. (see [numpy.cumsum](https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html)).
    ///
    /// For example, summing the array `[[1000, 200], [30, 4]]` along the first or the second axes results in the arrays `[[1000, 200], [1030, 204]]` or `[[1000, 1200], [30, 34]]`, respectively.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `axis` - axis along which the cumulative sum is computed
    ///
    /// # Returns
    ///
    /// New cumulative sum node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.cum_sum(n1, 1).unwrap();
    /// ```
    pub fn cum_sum(&self, a: Node, axis: u64) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::CumSum(axis))
    }

    /// Adds a node that permutes an array along given axes (see [numpy.transpose](https://numpy.org/doc/stable/reference/generated/numpy.transpose.html)). This function generalizes matrix transposition.
    ///
    /// For example, permutation of an array of shape `[a,b,c]` with permutation `[2,0,1]` results in an array of shape `[c,a,b]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `axes` - indices of the axes of `a`
    ///
    /// # Returns
    ///
    /// New node with permuted axes
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0, 2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.permute_axes(n1, axes).unwrap();
    /// ```
    pub fn permute_axes(&self, a: Node, axes: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::PermuteAxes(axes))
    }

    /// Adds a node to the parent graph that inverts a given permutation.
    ///
    /// An input permutation should be given by a 1-dimensional array of length n, containing unique integers between 0 and n-1.
    /// The i-th element of an output array is output[i] = j if input[j] = i.
    ///
    /// This operation could be realized through [the Scatter operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)#Scatter).
    /// However, the Scatter operation poses a security risk as the corresponding map should hide empty output positions.
    /// This is usually done by padding an input array with dummy values such that its size is equal to the output size.
    /// Then, the Scatter map can be turned into a permutation, which can be easily split into a composition of random permutation maps.
    /// But permutation maps can be performed by Gather, thus making Scatter unnecessary.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `a` - node containing an array with permutation.
    #[doc(hidden)]
    pub fn inverse_permutation(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::InversePermutation)
    }

    /// Adds a node that extracts a sub-array with a given index. This is a special case of [get_slice](Graph::get_slice) and corresponds to single element indexing as in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, given an array `A` of shape `[a,b,c,d]`, its subarray `B` of shape `[c,d]` with index `[i,j]` can be extracted as follows
    ///
    /// `B = A[i,j,:,:]` (in the NumPy notation)
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `index` - index of a sub-array
    ///
    /// # Returns
    ///
    /// New node containing an extracted sub-array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let index = vec![2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.get(n1, index).unwrap();
    /// ```
    pub fn get(&self, a: Node, index: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Get(index))
    }

    /// Adds a node that extracts a sub-array corresponding to a given slice.
    ///
    /// Our slicing conventions follow [the NumPy rules](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, given an array `A` of shape `[a,b]`, its subarray `B` containing only the last 3 rows of `A` can be extracted as follows
    ///
    /// `get_slice(A, [-3::])[i,j] = A[a-3+i,j]`.
    ///
    /// Slices are defined as vectors of [SliceElements](SliceElement) that have 3 possible types:
    ///
    /// * [SingleIndex(`i64`)](SliceElement::SingleIndex) is used to extract all the elements with a given index in a respective dimension,
    /// * [SubArray(`Option<i64>, Option<i64>, Option<i64>`)](SliceElement::SubArray) describes the range of indices that should be extracted over a certain dimension (similar to the `a:b:c` notation in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html))
    /// * [Ellipsis](SliceElement::Ellipsis) describes several consecutive dimensions that must be extracted in full, e.g. the slice `[i,...,j]` can be used to extract all the elements with the index `i` in the first dimension and the index `j` in the last one, while the indices of all the other dimensions have no constraints. See [the NumPy slicing](https://numpy.org/doc/stable/user/basics.indexing.html) for more details.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `slice` - array slice
    ///
    /// # Returns
    ///
    /// New node containing an extracted sub-array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, SliceElement};
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let slice = vec![SliceElement::Ellipsis, SliceElement::SubArray(None, None, Some(-2))];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.get_slice(n1, slice).unwrap();
    /// ```
    pub fn get_slice(&self, a: Node, slice: Slice) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::GetSlice(slice))
    }

    /// Adds a node that reshapes a value to a given compatible type (similar to [numpy.reshape](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.reshape.html?highlight=reshape#numpy.ndarray.reshape), but more general). Specifically,
    ///
    /// * if the input value is an array, it can be reshaped to any array with the same number of elements;
    /// * if the input value in the flattened form contains `n` arrays or scalars, it can be reshaped to any type with the same number of arrays and scalars. Each array can be reshaped as in the above rule.
    ///
    /// For example, an array of shape `[3,10,5]` can be reshaped to `[2,75]`. A tuple with arrays of shapes `[3,4]`, `[12]`, `[2,6]` can be reshaped to a vector with 3 array elements of shape `[2,2,3]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a value
    /// * `new_type` - type
    ///
    /// # Returns
    ///
    /// New node with a reshaped value
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let old_t = array_type(vec![3, 2, 3], INT32);
    /// let new_t = array_type(vec![3,6], INT32);
    /// let n1 = g.input(old_t).unwrap();
    /// let n2 = g.reshape(n1, new_t).unwrap();
    /// ```
    pub fn reshape(&self, a: Node, new_type: Type) -> Result<Node> {
        let size_estimate = get_size_estimation_in_bits(new_type.clone());
        if size_estimate.is_err() {
            return Err(runtime_error!(
                "Trying to add a reshape node with invalid type size: {:?}",
                size_estimate
            ));
        }
        if size_estimate? > type_size_limit_constants::MAX_INDIVIDUAL_NODE_SIZE {
            return Err(runtime_error!(
                "Trying to add a reshape node larger than MAX_INDIVIDUAL_NODE_SIZE"
            ));
        }
        self.add_node(vec![a], vec![], Operation::Reshape(new_type))
    }

    /// Adds a node creating a random value of a given type.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `output_type` - type of a constant
    ///
    /// # Returns
    ///
    /// New random node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.random(t).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn random(&self, output_type: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Random(output_type))
    }

    /// Adds a node creating a random permutation map of a one-dimensional array of length `n`.
    ///
    /// This operation generates a random array of all 64-bit integers from 0 to n-1 in random order.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `n` - length of permutation
    ///
    /// # Returns
    ///
    /// New random permutation node
    #[doc(hidden)]
    pub fn random_permutation(&self, n: u64) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::RandomPermutation(n))
    }

    /// Adds a node returning the Cuckoo hash map of an input array of binary strings using provided hash functions.
    ///
    /// Hash functions are defined as an array of binary matrices.
    /// The hash of an input string is a product of one of these matrices and this string.
    /// Hence, the last dimension of these matrices should coincide with the length of input strings.
    ///
    /// Random matrices yield a better success probability of hashing.
    ///
    /// If the input array has shape `[..., n, b]` and hash matrices are given as an `[h, m, b]`-array,
    /// then the hash map is an array of shape `[..., 2^m]`.
    /// The hash table element with index `[..., i]` is equal to `j` if the `[..., j]`-th input `b`-bit string is hashed to `i` by some of the given hash functions.
    ///
    /// The number of hash matrices (the first dimension of hash matrices) must be at least 3.
    ///
    /// A bigger ratio `m/n` leads to higher success probability (recommended one is `>=2`)    
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// - `array` - input array of binary strings of shape [..., n, b]
    /// - `hash_matrices` - random binary [h, m, b]-array.
    ///
    /// # Returns
    ///
    /// New CuckooHash node
    #[doc(hidden)]
    pub fn cuckoo_hash(&self, array: Node, hash_matrices: Node) -> Result<Node> {
        self.add_node(vec![array, hash_matrices], vec![], Operation::CuckooHash)
    }

    /// Adds a node that, given an input multidimensional array A, binary one-dimensional array B (first dimension is n in both array) and starting value v, computes the following iteration
    ///
    /// output[i] = A[i-1] + B[i-1] * output[i-1]
    ///
    /// where i in {1,...,n} and output[0] = v.
    /// This is similar to computing cumulative sums of consecutive elements (segments) of the input array A.
    /// The locations of these segments are defined by the binary array B.
    ///
    /// This iteration is used in the Duplication protocol (see mpc::mpc_psi) and is done locally by one of the computing parties.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// - `input_array` - input array whose rows are summed within the iteration
    /// - `binary_array` - binary array indicating whether a row of the input array should be added to a previous row of the output array
    /// - `first_row` - first row of the output array
    ///
    /// # Returns
    ///
    /// New SegmentCumSum node containing the output array
    #[doc(hidden)]
    pub fn segment_cumsum(
        &self,
        input_array: Node,
        binary_array: Node,
        first_row: Node,
    ) -> Result<Node> {
        self.add_node(
            vec![input_array, binary_array, first_row],
            vec![],
            Operation::SegmentCumSum,
        )
    }

    /// Adds a node that computes sharding of a given table according to a given sharding config.
    /// Sharding config contains names of the columns whose hashed values are used for sharding.
    /// The size of each shard (i.e., the number of rows) and the number of shards is given in the sharding config.
    /// The number of shards should be smaller than 700.
    ///
    ///
    /// If some resulting shards don't have `shard_size` elements, they're padded with zeros to reach this size.
    /// If the size of some shards exceeds `shard_size`, sharding fails.
    ///
    /// To choose these parameters, consult [the following paper](http://wwwmayr.informatik.tu-muenchen.de/personen/raab/publ/balls.pdf).
    /// Note that for large shard sizes and small number of shards, it holds that
    ///
    /// `shard_size = num_input_rows / num_shards + alpha * sqrt(2 * num_input_rows / num_shards * log(num_shards))`.
    ///
    /// With `alpha = 2`, it is possible to achieve failure probability 2^(-40) if `num_shards < 700` and `shard_size > 2^17`.
    ///
    ///
    /// Each shard is accompanied by a Boolean mask indicating whether a corresponding row stems from the input table or padded (1 if a row comes from input).
    /// The output is given in the form of a tuple of `(mask, shard)`, where `mask` is a binary array and `shard` is a table, i.e., named tuple.
    ///
    /// **WARNING**: this function cannot be compiled to an MPC protocol.
    ///
    /// # Arguments
    ///
    /// - `input_table` - named tuple of arrays containing data for sharding
    /// - `shard_config` - parameters of sharding: number of shards, shard size and names of columns that are hashed in sharding
    ///
    /// # Returns
    ///
    /// New Shard node containing a tuple of shards
    #[doc(hidden)]
    pub fn shard(&self, input_table: Node, shard_config: ShardConfig) -> Result<Node> {
        self.add_node(vec![input_table], vec![], Operation::Shard(shard_config))
    }

    /// Adds a node that converts a switching map array into a random tuple of the following components:
    /// - a permutation map array with deletion (some indices of this map are uniformly random, see below),
    /// - a tuple of duplication map array and duplication bits,
    /// - a permutation map array without deletion.
    ///
    /// The composition of these maps is equal to the input switching map, which is an array containing non-unique indices of some array.
    ///
    /// To create a permutation with deletion, this operation first groups identical indices of the input map together and shifts other indices accordingly, e.g.
    ///
    /// [1, 4, 5, 7, 2, 4] -> [1, 4, 4, 5, 7, 2].
    ///
    /// This can be done by permutation p = [1, 2, 6, 3, 4, 5].
    /// Then, it replaces copies with unique random indices not present in the switching map, e.g.
    ///
    /// [1, 4, 4, 5, 7, 2] -> [1, 4, 3, 5, 7, 2].
    ///
    ///
    /// A duplication map is a tuple of two one-dimensional arrays of length `n`.
    /// The first array contains indices from `[0,n]` in the increasing order with possible repetitions.
    /// The second array contains only zeros and ones.
    /// If its i-th element is zero, it means that the duplication map doesn't change the i-th element of an array it acts upon.
    /// If map's i-th element is one, then the map copies the previous element of the result.
    /// This rules can be summarized by the following equation
    ///
    /// duplication_indices[i] = duplication_bits[i] * duplication_indices[i-1] + (1 - duplication_bits[i]) * i.
    ///
    /// A duplication map is created from the above switching map with grouped indices, replacing the first index occurrence with 0 and other copies with 1, e.g.
    ///
    ///  [1, 4, 4, 5, 7, 2] -> ([0, 1, 1, 3, 4, 5], [0, 0, 1, 0, 0, 0]).
    ///
    /// The last permutation is the inverse of the above permutation p, i.e.
    ///
    /// [1, 2, 4, 5, 6, 3].
    ///
    /// This operation supports vectorization.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// - `switching_map` - an array of one-dimensional arrays containing non-unique indices of some array of length `n` (usually a simple hash table),
    /// - `n` - length of an array that can be mapped by the above switching map.
    ///
    /// # Returns
    ///
    /// New DecomposeSwitchingMap node
    #[doc(hidden)]
    pub fn decompose_switching_map(&self, switching_map: Node, n: u64) -> Result<Node> {
        self.add_node(
            vec![switching_map],
            vec![],
            Operation::DecomposeSwitchingMap(n),
        )
    }

    /// Adds a node that converts a Cuckoo hash table to a random permutation.
    ///
    /// Conversion is done via replacing dummy hash elements by random indices such that the resulting array constitute a permutation.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `cuckoo_map` - an array containing a Cuckoo hash map with dummy values
    ///
    /// # Returns
    ///
    /// New CuckooToPermutation node
    #[doc(hidden)]
    pub fn cuckoo_to_permutation(&self, cuckoo_map: Node) -> Result<Node> {
        self.add_node(vec![cuckoo_map], vec![], Operation::CuckooToPermutation)
    }

    /// Adds a node that joins a sequence of arrays governed by a given shape.
    ///
    /// The input arrays should have the same shape or be able to be broadcast to the same shape.
    ///
    /// For example, stacking 2 arrays of shapes `[2,2]` and `[2,1]` with the outer shape `[2]` works as follows
    ///
    /// `stack(arrays=[[[1,2],[3,4]], [5,6]], shape=[2]) = [[[1,2],[3,4]], [[5,5], [6,6]]]`
    ///
    /// # Arguments
    ///
    /// * `nodes` - vector of nodes containing arrays
    /// * `outer_shape` - shape defining how the input arrays are arranged in the resulting array
    ///
    /// # Returns
    ///
    /// New stack node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let shape = vec![2];
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.stack(vec![n1,n2], shape).unwrap();
    /// ```
    pub fn stack(&self, nodes: Vec<Node>, outer_shape: ArrayShape) -> Result<Node> {
        self.add_node(nodes, vec![], Operation::Stack(outer_shape))
    }

    /// Adds a node that joins a sequence of arrays along a given axis.
    /// This operation is similar to [the NumPy concatenate](https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html).
    ///
    /// The input arrays should have the same shape except in the given axis.
    ///
    /// # Arguments
    ///
    /// * `nodes` - vector of nodes containing arrays
    /// * `axis` - axis along which the above arrays are joined
    ///
    /// # Returns
    ///
    /// New Concatenate node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![3, 2, 10], INT32);
    /// let shape = vec![2];
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.concatenate(vec![n1,n2], 2).unwrap();
    /// ```
    pub fn concatenate(&self, nodes: Vec<Node>, axis: u64) -> Result<Node> {
        self.add_node(nodes, vec![], Operation::Concatenate(axis))
    }

    /// Adds a node creating a constant of a given type and value.
    ///
    /// # Arguments
    ///
    /// * `output_type` - type of a constant
    /// * `value` - value of a constant
    ///
    /// # Returns
    ///
    /// New constant node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let v = Value::from_scalar(0, BIT).unwrap();
    /// let n = g.constant(t, v).unwrap();
    /// ```
    pub fn constant(&self, output_type: Type, value: Value) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Constant(output_type, value))
    }

    /// Adds a node converting an integer array or scalar to the binary form.
    ///
    /// Given an array of shape `[a,b,c]` and scalar type `st`, this node returns an array of shape `[a,b,c,s]` where `s` is the bit size of `st`. For example, an array of shape `[1,2,3]` with `INT32` entries will be converted to a binary array of shape `[1,2,3,32]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing an array or scalar
    ///
    /// # Returns
    ///
    /// New node converting an array/scalar to the binary form
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.a2b(n1).unwrap();
    /// ```
    pub fn a2b(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::A2B)
    }

    /// Adds a node converting a binary array to an array of a given scalar type.
    ///
    /// Given a binary array of shape `[a,b,c]` and a scalar type `st` of bit size `c`, this node returns an array of shape `[a,b]` with `st` entries. For example, a binary array of shape `[2,3,32]` can be converted to an array of shape `[2,3]` with `INT32` entries.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array or scalar
    /// * `scalar_type` - scalar type
    ///
    /// # Returns
    ///
    /// New node converting an array from the binary form
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 32], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.b2a(n1, INT32).unwrap();
    /// ```
    pub fn b2a(&self, a: Node, scalar_type: ScalarType) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::B2A(scalar_type))
    }

    /// Adds a node that creates a tuple from several (possibly, zero) elements.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of nodes
    ///
    /// # Returns
    ///
    /// New node with a tuple
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1,n2]).unwrap();
    /// ```
    pub fn create_tuple(&self, elements: Vec<Node>) -> Result<Node> {
        self.add_node(elements, vec![], Operation::CreateTuple)
    }

    /// Adds a node that creates a vector from several (possibly, zero) elements of the same type.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of nodes
    ///
    /// # Returns
    ///
    /// New node with a created vector
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// ```
    pub fn create_vector(&self, element_type: Type, elements: Vec<Node>) -> Result<Node> {
        self.add_node(elements, vec![], Operation::CreateVector(element_type))
    }

    /// Adds a node that creates a named tuple from several (possibly, zero) elements.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of pairs (node name, node)
    ///
    /// # Returns
    ///
    /// New node creating a named tuple
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// ```
    pub fn create_named_tuple(&self, elements: Vec<(String, Node)>) -> Result<Node> {
        let mut nodes = vec![];
        let mut names = vec![];
        for (name, node) in elements {
            nodes.push(node);
            names.push(name);
        }
        self.add_node(nodes, vec![], Operation::CreateNamedTuple(names))
    }

    /// Adds a node that extracts an element of a tuple.
    ///
    /// # Arguments
    ///
    /// * `tuple` - node containing a tuple
    /// * `index` - index of a tuple element between 0 and tuple length minus 1
    ///
    /// # Returns
    ///
    /// New node with an extracted element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1, n2]).unwrap();
    /// let n4 = g.tuple_get(n3, 1).unwrap();
    /// ```
    pub fn tuple_get(&self, tuple: Node, index: u64) -> Result<Node> {
        self.add_node(vec![tuple], vec![], Operation::TupleGet(index))
    }

    /// Adds a node that extracts an element of a named tuple.
    ///
    /// # Arguments
    ///
    /// * `tuple` - node containing a named tuple
    /// * `key` - key of a tuple element
    ///
    /// # Returns
    ///
    /// New node extracting a tuple element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// let n4 = g.named_tuple_get(n3, "node2".to_owned()).unwrap();
    /// ```
    pub fn named_tuple_get(&self, tuple: Node, key: String) -> Result<Node> {
        self.add_node(vec![tuple], vec![], Operation::NamedTupleGet(key))
    }

    /// Adds a node that extracts an element of a vector.
    ///
    /// # Arguments
    ///
    /// * `vec` - node containing a vector
    /// * `index` - node containing the index of a tuple element
    ///
    /// # Returns
    ///
    /// New node extracting a vector element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT32, INT32, array_type, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n4 = g.vector_get(n3, index).unwrap();
    /// ```
    pub fn vector_get(&self, vec: Node, index: Node) -> Result<Node> {
        self.add_node(vec![vec, index], vec![], Operation::VectorGet)
    }

    /// Adds a node that takes vectors V<sub>1</sub>(n, t<sub>1</sub>), V<sub>2</sub>(n, t<sub>2</sub>), ..., V<sub>k</sub>(n, t<sub>k</sub>) of the same length and returns a vector V(n, tuple(t<sub>1</sub>, ..., t<sub>k</sub>)) (similar to [zip](https://doc.rust-lang.org/stable/std/iter/fn.zip.html)).
    ///
    /// # Arguments
    ///
    /// `nodes` - vector of nodes containing input vectors
    ///
    /// # Returns
    ///
    /// New zip node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type, vector_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let vec_t = vector_type(3, t);
    /// let n1 = g.input(vec_t.clone()).unwrap();
    /// let n2 = g.input(vec_t.clone()).unwrap();
    /// let n3 = g.zip(vec![n1,n2]).unwrap();
    /// ```
    pub fn zip(&self, nodes: Vec<Node>) -> Result<Node> {
        self.add_node(nodes, vec![], Operation::Zip)
    }

    /// Adds a node that creates a vector with `n` copies of a value of a given node.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a value
    /// * `n` - number of copies
    ///
    /// # Returns
    ///
    /// New repeat node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.repeat(n1, 10).unwrap();
    /// ```
    pub fn repeat(&self, a: Node, n: u64) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Repeat(n))
    }

    /// Adds a node that calls another graph with inputs contained in given nodes.
    ///
    /// The input graph must be finalized and have as many inputs as the number of provided arguments.
    ///
    /// For example, let `G` be a graph implementing the function `max(x,0)`, then `call(G, [17]) = max(17, 0)`.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph with `n` input nodes
    /// * `arguments` - vector of `n` nodes
    ///
    /// # Returns
    ///
    /// New call node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    ///
    /// let g1 = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g1.input(t.clone()).unwrap();
    /// let n2 = g1.repeat(n1, 10).unwrap();
    /// let n3 = g1.vector_to_array(n2).unwrap();
    /// n3.set_as_output().unwrap();
    /// g1.finalize().unwrap();
    ///
    /// let g2 = c.create_graph().unwrap();
    /// let n4 = g2.input(t).unwrap();
    /// let n5 = g2.add(n4.clone(), n4).unwrap();
    /// let n6 = g2.call(g1, vec![n5]).unwrap();
    /// ```
    pub fn call(&self, graph: Graph, arguments: Vec<Node>) -> Result<Node> {
        self.add_node(arguments, vec![graph], Operation::Call)
    }

    /// Adds a node that iteratively computes a given finalized graph on the elements of a given vector and updates the state value accordingly.
    ///
    /// This node calls another `graph` with 2 input nodes `old_state` and `input` and an output node that returns a [tuple](Type::Tuple) `(new_state, output)`. This graph is used to map the elements of a given vector `V` to another vector `W` as follows:
    /// ```text
    /// graph(state_0, V[0]) -> (state1, W[0]),
    /// graph(state_1, V[1]) -> (state2, W[1]),
    /// ...
    /// graph(state_k, V[k]) -> (final_state, W[k]).
    /// ```
    /// The output is a [tuple](Type::Tuple) `(final_state, W)`. The initial state `state_0` should be provided as an argument.
    ///
    /// This node generalize `map` and `reduce` procedures (see [MapReduce](https://en.wikipedia.org/wiki/MapReduce) for more details).
    ///
    /// For example, let `G` be a graph implementing the function `max(x,0)` and incrementing `state` if its output is negative, then `iterate(G, 0, [-1,2,0,3,2]) = (1, [0,2,0,3,2])`. The final state is equal to the number of negative values in the input vector.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph with 2 input nodes of types T<sub>s</sub> and T<sub>i</sub> and returning a tuple of type (T<sub>s</sub>, T<sub>o</sub>)
    /// * `state` - node containing an initial state of type T<sub>s</sub>
    /// * `input` - node containing a vector with elements of type T<sub>i</sub>
    ///
    /// # Returns
    ///
    /// New iterate node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, BIT, scalar_type, vector_type};
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::ops::utils::constant_scalar;
    /// let c = create_context().unwrap();
    ///
    /// let t_s = scalar_type(BIT);
    /// let t = scalar_type(INT32);
    /// let vec_t = vector_type(10, t.clone());
    ///
    /// // Graph that outputs 0 at even indices or input value at odd indices.
    /// let g1 = c.create_graph().unwrap();
    /// {
    ///     let old_state = g1.input(t_s.clone()).unwrap();
    ///     let input = g1.input(t.clone()).unwrap();
    ///     let result = g1.mixed_multiply(input, old_state.clone()).unwrap();
    ///     let new_state = g1.add(old_state, constant_scalar(&g1, 1, BIT).unwrap()).unwrap();
    ///     let out_tuple = g1.create_tuple(vec![new_state, result]).unwrap();
    ///     out_tuple.set_as_output().unwrap();
    ///     g1.finalize().unwrap();
    /// }
    ///
    /// let g2 = c.create_graph().unwrap();
    /// let initial_state = constant_scalar(&g2, 0, BIT).unwrap();
    /// let input_vector = g2.input(vec_t).unwrap();
    /// g2.iterate(g1, initial_state, input_vector).unwrap();
    /// ```
    pub fn iterate(&self, graph: Graph, state: Node, input: Node) -> Result<Node> {
        self.add_node(vec![state, input], vec![graph], Operation::Iterate)
    }

    /// Adds a node converting an array to a vector.
    ///
    /// Given an array of shape `[a,b,c]`, this node returns a vector of `a` arrays of shape `[b,c]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing an array
    ///
    /// # Returns
    ///
    /// New node converting an array to a vector
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, scalar_type, INT32, UINT32};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![4, 3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.array_to_vector(n1).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n3 = g.vector_get(n2.clone(), index).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_vector());
    /// assert_eq!(n3.get_type().unwrap().get_shape(), vec![3,2]);
    /// ```    
    pub fn array_to_vector(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::ArrayToVector)
    }

    /// Adds a node converting a vector to an array.
    ///
    /// Given a vector of `a` arrays of shape `[b,c]`, this node returns an array of shape `[a,b,c]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing a vector
    ///
    /// # Returns
    ///
    /// New node converting a vector to an array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_array());
    /// assert_eq!(n2.get_type().unwrap().get_shape(), vec![4, 3, 2]);
    /// ```
    pub fn vector_to_array(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::VectorToArray)
    }

    /// Adds a node creating an array from the elements of an input array indexed by another array along a given axis.
    ///
    /// Given an input array, this node replaces the dimension `axis` with the dimensions introduced by the indexing array.
    ///
    /// Indices must be unique to prevent possible duplication of shares/ciphertexts.
    /// Such duplicates might cause devastating data leakage.
    ///
    /// This operation is similar to [the NumPy take operation](https://numpy.org/doc/stable/reference/generated/numpy.take.html).
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `input` - node containing an input array
    /// `indices` - node containing indices
    /// `axis` - index of the axis along which indices are chosen
    ///
    /// # Returns
    ///
    /// New Gather node
    #[doc(hidden)]
    pub fn gather(&self, input: Node, indices: Node, axis: u64) -> Result<Node> {
        self.add_node(vec![input, indices], vec![], Operation::Gather(axis))
    }

    /// Checks that the graph has an output node and finalizes the graph.
    ///
    /// After finalization the graph can't be changed.
    ///
    /// # Returns
    ///
    /// Finalized graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn finalize(&self) -> Result<Graph> {
        let output_node = self.body.borrow_mut().output_node.clone();
        match output_node {
            Some(_) => {
                self.body.borrow_mut().finalized = true;
                Ok(self.clone())
            }
            None => Err(runtime_error!("Output node is not set")),
        }
    }

    /// Returns the vector of nodes contained in the graph in order of construction.
    ///
    /// # Returns
    ///
    /// Vector of nodes of the graph
    pub fn get_nodes(&self) -> Vec<Node> {
        self.body.borrow().nodes.clone()
    }

    /// Promotes a given node to the output node of the parent graph.
    ///
    /// # Arguments
    ///
    /// `output_node` - node to be set as output
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// g.set_output_node(n2).unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn set_output_node(&self, output_node: Node) -> Result<()> {
        let current_output_node = self.body.borrow().output_node.clone();
        match current_output_node {
            Some(_) => Err(runtime_error!("Output node is already set")),
            None => {
                if output_node.get_graph() != *self {
                    Err(runtime_error!("Output node has to be from the same graph"))
                } else {
                    self.body.borrow_mut().output_node = Some(output_node.downgrade());
                    Ok(())
                }
            }
        }
    }

    /// Returns the output node of the graph.
    ///
    /// # Returns
    ///
    /// Output node of the graph
    pub fn get_output_node(&self) -> Result<Node> {
        let current_output_node = self.body.borrow().output_node.clone();
        match current_output_node {
            Some(output_node) => Ok(output_node.upgrade()),
            None => Err(runtime_error!("Output node is not set")),
        }
    }

    /// Returns the ID of the graph.
    ///
    /// A graph ID is a serial number of a graph between `0` and `n-1` where `n` is the number of graphs in the parent context.
    ///
    /// # Returns
    ///
    /// Graph ID
    pub fn get_id(&self) -> u64 {
        self.body.borrow().id
    }

    /// Returns the number of the graph nodes.
    ///
    /// # Returns
    ///
    /// Number of the graph nodes
    pub fn get_num_nodes(&self) -> u64 {
        self.body.borrow().nodes.len() as u64
    }

    /// Returns the node corresponding to a given ID.
    ///
    /// # Arguments
    ///
    /// `id` - node ID
    ///
    /// # Returns
    ///
    /// Node with a given ID
    pub fn get_node_by_id(&self, id: u64) -> Result<Node> {
        let nodes = &self.body.borrow().nodes;
        if id >= nodes.len() as u64 {
            Err(runtime_error!("Invalid id for the node retrieval"))
        } else {
            Ok(nodes[id as usize].clone())
        }
    }

    /// Returns the context of the graph nodes.
    ///
    /// # Returns
    ///
    /// Context of the graph
    pub fn get_context(&self) -> Context {
        self.body.borrow().context.upgrade()
    }

    /// Adds a node computing a given custom operation.
    ///
    /// Custom operations can be created by the user as public structs implementing the [CustomOperationBody](../custom_ops/trait.CustomOperationBody.html).
    ///
    /// # Arguments
    ///
    /// * `op` - custom operation
    /// * `arguments` - vector of nodes used as input for the custom operation
    ///
    /// # Returns
    ///
    /// New custom operation node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, BIT};
    /// # use ciphercore_base::custom_ops::{CustomOperation, Not};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.custom_op(CustomOperation::new(Not {}), vec![n1]).unwrap();
    /// ```
    pub fn custom_op(&self, op: CustomOperation, arguments: Vec<Node>) -> Result<Node> {
        self.add_node(arguments, vec![], Operation::Custom(op))
    }

    /// Adds a node which logs its input at runtime, and returns the input.
    /// This is intended to be used for debugging.
    ///
    /// # Arguments
    ///
    /// * `message` - Informational message to be printed
    /// * `input` - Node to be printed
    ///
    /// # Returns
    ///
    /// The value of the node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, BIT};
    /// # use ciphercore_base::custom_ops::{CustomOperation, Not};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.print("n1:".into(), n1).unwrap();
    /// ```
    pub fn print(&self, message: String, input: Node) -> Result<Node> {
        self.add_node(vec![input], vec![], Operation::Print(message))
    }

    /// Adds a node which fails the execution at runtime if `condition` is false, and returns the `input` otherwise.
    /// This is intended to be used for debugging.
    ///
    /// # Arguments
    ///
    /// * `message` - message to be returned for the failed assertion.
    /// * `condition` - BIT to be checked in the assertion.
    /// * `input` - Node to be returned for pass-through.
    ///
    /// # Returns
    ///
    /// The value of the node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, scalar_type, BIT};
    /// # use ciphercore_base::custom_ops::{CustomOperation, Not};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let cond = g.input(scalar_type(BIT)).unwrap();
    /// let t = array_type(vec![3, 2], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.assert("Condition".into(), cond, n1).unwrap();
    /// ```
    pub fn assert(&self, message: String, condition: Node, input: Node) -> Result<Node> {
        self.add_node(vec![condition, input], vec![], Operation::Assert(message))
    }
}

/// Methods which aren't supposed to be imported in Python.
impl Graph {
    /// Adds an operation node to the graph and returns it.
    ///
    /// # Arguments
    ///
    /// * `node_dependencies` - vector of nodes necessary to perform the given operation
    /// * `graph_dependencies` - vector of graphs necessary to perform the given operation
    /// * `operation` - operation performed by the node
    ///
    /// # Returns
    ///
    /// New operation node that gets added
    pub fn add_node(
        &self,
        node_dependencies: Vec<Node>,
        graph_dependencies: Vec<Graph>,
        operation: Operation,
    ) -> Result<Node> {
        if self.is_finalized() {
            return Err(runtime_error!("Can't add a node to a finalized graph"));
        }
        for dependency in &node_dependencies {
            if dependency.get_graph() != *self
                || dependency.get_id() >= self.body.borrow().nodes.len() as u64
                || self.body.borrow().nodes[dependency.get_id() as usize] != *dependency
            {
                return Err(runtime_error!(
                    "Can't add a node with invalid node dependencies"
                ));
            }
        }
        for dependency in &graph_dependencies {
            if !dependency.is_finalized() {
                return Err(runtime_error!(
                    "Can't add a node with not finilized graph dependency"
                ));
            }
            if dependency.get_id() >= self.get_id() {
                return Err(runtime_error!(
                    "Can't add a node with graph dependency with bigger id. {} >= {}",
                    dependency.get_id(),
                    self.get_id()
                ));
            }
            if dependency.get_context() != self.get_context() {
                return Err(runtime_error!(
                    "Can't add a node with graph dependency from different context"
                ));
            }
        }
        let id = self.body.borrow().nodes.len() as u64;
        let result = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: self.downgrade(),
                node_dependencies: node_dependencies.iter().map(|n| n.downgrade()).collect(),
                graph_dependencies: graph_dependencies.iter().map(|g| g.downgrade()).collect(),
                operation,
                id,
            })),
        };
        {
            let mut cell = self.body.borrow_mut();
            cell.nodes.push(result.clone());
        }
        let mut context_has_type_checker = false;
        {
            let context = self.get_context();
            let mut context_cell = context.body.borrow_mut();
            let type_checker = &mut context_cell.type_checker;
            if type_checker.is_some() {
                context_has_type_checker = true;
            }
        }
        if context_has_type_checker {
            let type_checking_result = result.get_type();
            if type_checking_result.is_err() {
                self.remove_last_node(result)?;
                return Err(type_checking_result.expect_err("Should not be here"));
            }
            let type_result = type_checking_result?;

            let size_estimate = get_size_estimation_in_bits(type_result);
            if size_estimate.is_err() {
                self.remove_last_node(result)?;
                return Err(runtime_error!("Trying to add a node with invalid size"));
            }
            if size_estimate? > type_size_limit_constants::MAX_INDIVIDUAL_NODE_SIZE {
                self.remove_last_node(result)?;
                return Err(runtime_error!(
                    "Trying to add a node larger than MAX_INDIVIDUAL_NODE_SIZE"
                ));
            }

            let context = self.get_context();
            let size_checking_result = context.try_update_total_size(result.clone());
            if size_checking_result.is_err() {
                self.remove_last_node(result)?;
                return Err(size_checking_result.expect_err("Should not be here"));
            }
        }
        Ok(result)
    }

    fn remove_last_node(&self, n: Node) -> Result<()> {
        if n.get_graph() != *self {
            return Err(runtime_error!(
                "The node to be removed from a different graph"
            ));
        }
        {
            let cell = self.body.borrow();
            if n != *cell
                .nodes
                .last()
                .ok_or_else(|| runtime_error!("Nodes list is empty"))?
            {
                return Err(runtime_error!(
                    "The node to be removed is not the last node"
                ));
            }
        };
        let context = self.get_context();
        context.unregister_node(n.clone())?;
        let mut context_body = context.body.borrow_mut();
        if let Some(tc) = &mut context_body.type_checker {
            tc.unregister_node(n)?;
        }
        let mut cell = self.body.borrow_mut();
        cell.nodes.pop();
        Ok(())
    }

    pub(crate) fn nop(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::NOP)
    }

    pub(crate) fn prf(&self, key: Node, iv: u64, output_type: Type) -> Result<Node> {
        self.add_node(vec![key], vec![], Operation::PRF(iv, output_type))
    }

    pub(crate) fn permutation_from_prf(&self, key: Node, iv: u64, n: u64) -> Result<Node> {
        self.add_node(vec![key], vec![], Operation::PermutationFromPRF(iv, n))
    }

    pub(super) fn is_finalized(&self) -> bool {
        self.body.borrow().finalized
    }

    pub(super) fn check_finalized(&self) -> Result<()> {
        if !self.is_finalized() {
            return Err(runtime_error!("Graph is not finalized"));
        }
        Ok(())
    }

    fn make_serializable(&self) -> SerializableGraph {
        let output_node = match self.get_output_node() {
            Ok(n) => Some(n.get_id()),
            Err(_) => None,
        };
        Arc::new(SerializableGraphBody {
            finalized: self.is_finalized(),
            nodes: self
                .get_nodes()
                .iter()
                .map(|n| n.make_serializable())
                .collect(),
            output_node,
        })
    }

    fn downgrade(&self) -> WeakGraph {
        WeakGraph {
            body: Arc::downgrade(&self.body),
        }
    }

    #[doc(hidden)]
    pub fn add_annotation(&self, annotation: GraphAnnotation) -> Result<Graph> {
        self.get_context().add_graph_annotation(self, annotation)?;
        Ok(self.clone())
    }

    pub fn get_annotations(&self) -> Result<Vec<GraphAnnotation>> {
        self.get_context().get_graph_annotations(self.clone())
    }

    /// Rearrange given input values according to the names and the order of the related input nodes.
    ///
    /// For example, given a graph with the first input node named 'A' and the second one named 'B' and input values `{'B': v, 'A': w}`, this function returns a vector `[w, v]`.
    ///
    /// # Arguments
    ///
    /// `values` - hashmap of values keyed by node names
    ///
    /// # Returns
    ///
    /// Vector of values arranged by node names
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// n1.set_name("input1").unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// n2.set_name("input2").unwrap();
    ///
    /// let mut input_map = HashMap::new();
    /// input_map.insert("input2", 2);
    /// input_map.insert("input1", 1);
    /// let ordered_input = g.prepare_input_values(input_map).unwrap();
    ///
    /// assert_eq!(vec![1,2], ordered_input);
    /// ```
    pub fn prepare_input_values<T: Clone>(&self, values: HashMap<&str, T>) -> Result<Vec<T>> {
        self.get_context()
            .prepare_input_values(self.clone(), values)
    }
}
type WeakGraphBodyPointer = Weak<AtomicRefCell<GraphBody>>;

struct WeakGraph {
    body: WeakGraphBodyPointer,
}

impl WeakGraph {
    //upgrade function panics if the the Graph pointer it downgraded from went out of scope
    fn upgrade(&self) -> Graph {
        Graph {
            body: self.body.upgrade().unwrap(),
        }
    }
}
impl Clone for WeakGraph {
    fn clone(&self) -> Self {
        WeakGraph {
            body: self.body.clone(),
        }
    }
}

#[doc(hidden)]
/// Various node-related properties which aren't used in the graph building
/// or type inference, but can be used in node expansion or MPC compilation.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum NodeAnnotation {
    AssociativeOperation,
    Private,
    Send(u64, u64), // (sender_index, receiver_index); indices belong to the set 0..PARTIES
    PRFMultiplication,
    PRFB2A,
    PRFTruncate,
}

#[doc(hidden)]
/// Various graph-related properties which aren't used in the graph building
/// or type inference, but can be used in node expansion or MPC compilation.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum GraphAnnotation {
    AssociativeOperation,
    OneBitState,
    SmallState,
}

struct ContextBody {
    finalized: bool,
    graphs: Vec<Graph>,
    main_graph: Option<WeakGraph>,
    /// graph_id -> name
    graphs_names: HashMap<u64, String>,
    /// name -> graph_id
    graphs_names_inverse: HashMap<String, u64>,
    /// (graph_id, node_id) -> name
    nodes_names: HashMap<(u64, u64), String>,
    /// graph_id -> (name -> node_id)
    nodes_names_inverse: HashMap<u64, HashMap<String, u64>>,
    /// (graph_id, node_id) -> NodeAnnotation's
    nodes_annotations: HashMap<(u64, u64), Vec<NodeAnnotation>>,
    /// (graph_id) -> GraphAnnotation's
    graphs_annotations: HashMap<u64, Vec<GraphAnnotation>>,
    total_size_nodes: u64,
    type_checker: Option<TypeInferenceWorker>,
}

type ContextBodyPointer = Arc<AtomicRefCell<ContextBody>>;

/// A structure that stores a pointer to a computation context that contains related computation graphs.
///
/// Context is a basic object to create computation graphs, arrange data flow between them and keep necessary information about them that is used for optimization, secure compilation and evaluation.
///
/// Context should have a main graph and be finalized in order to evaluate any of its graphs.
///
/// # Rust crates
///
/// [Clone] trait duplicates the pointer, not the underlying context.
///
/// [PartialEq] trait compares pointers, not the related contexts.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate maplit;
/// # fn main() {
/// # use ciphercore_base::graphs::{Context, create_context};
/// # use ciphercore_base::data_values::Value;
/// # use ciphercore_base::evaluators::random_evaluate;
/// # use ciphercore_base::data_types::{INT32, scalar_type};
/// # use ciphercore_base::errors::Result;
/// let context = || -> Result<Context> {
///     let context = create_context()?;
///     let graph = context.create_graph()?.set_name("main")?;
///     graph
///         .input(scalar_type(INT32))?
///         .set_name("a")?
///         .add(graph
///             .input(scalar_type(INT32))?
///             .set_name("b")?)?
///         .set_as_output()?;
///     graph.finalize()?.set_as_main()?;
///     context.finalize()?;
///     Ok(context)
/// }().unwrap();
///
/// let result = || -> Result<i32> {
///     let g = context.retrieve_graph("main")?;
///     let result = random_evaluate(
///         g.clone(),
///         g.prepare_input_values(
///             hashmap!{
///                 "a" => Value::from_scalar(123, INT32)?,
///                 "b" => Value::from_scalar(654, INT32)?,
///             },
///         )?,
///     )?;
///     let result = result.to_i32(INT32)?;
///     Ok(result)
/// }().unwrap();
///
/// assert_eq!(result, 777);
/// # }
/// ```
#[cfg_attr(feature = "py-binding", struct_wrapper)]
pub struct Context {
    body: ContextBodyPointer,
}

impl fmt::Debug for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Context {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match serde_json::to_string(&self) {
            Ok(s) => write!(f, "{s}"),
            Err(_err) => Err(fmt::Error::default()),
        }
    }
}

impl fmt::Display for Graph {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Graph[num_nodes={}]", self.get_num_nodes())
    }
}

impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Node[type={}]",
            self.get_type().map_err(|_| fmt::Error::default())?
        )
    }
}

#[derive(Serialize, Deserialize)]
struct SerializableContextBody {
    finalized: bool,
    graphs: Vec<SerializableGraph>,
    main_graph: Option<u64>,
    /// graph_id -> name
    graphs_names: Vec<(u64, String)>,
    /// (graph_id, node_id) -> name
    nodes_names: Vec<((u64, u64), String)>,
    /// (graph_id, node_id) -> NodeAnnotation's
    nodes_annotations: Vec<((u64, u64), Vec<NodeAnnotation>)>,
    /// (graph_id) -> GraphAnnotation's
    graphs_annotations: Vec<(u64, Vec<GraphAnnotation>)>,
}

impl SerializableContextBody {
    fn recover_original_graph(
        serializable_graph: SerializableGraph,
        context: Context,
    ) -> Result<Graph> {
        let result_graph = context.create_graph()?;
        for node in &serializable_graph.nodes {
            let mut node_dependencies = vec![];
            for id in &node.node_dependencies {
                let current_nodes = &result_graph.body.borrow().nodes;
                if *id >= current_nodes.len() as u64 {
                    return Err(runtime_error!("Non-existent node dependency"));
                }
                node_dependencies.push(current_nodes[*id as usize].clone());
            }
            let mut graph_dependencies = vec![];
            for id in &node.graph_dependencies {
                let context = result_graph.get_context();
                let current_graphs = &context.body.borrow().graphs;
                if *id >= current_graphs.len() as u64 {
                    return Err(runtime_error!("Non-existent graph dependency"));
                }
                graph_dependencies.push(current_graphs[*id as usize].clone());
            }
            result_graph.add_node(
                node_dependencies,
                graph_dependencies,
                node.operation.clone(),
            )?;
        }
        if let Some(id) = serializable_graph.output_node {
            let rebuilt_output_node = {
                let current_nodes = &result_graph.body.borrow().nodes;
                if id >= current_nodes.len() as u64 {
                    return Err(runtime_error!("Non-existent output node"));
                }
                current_nodes[id as usize].clone()
            };
            result_graph.set_output_node(rebuilt_output_node)?;
        }
        if serializable_graph.finalized {
            result_graph.finalize()?;
        }
        Ok(result_graph)
    }

    fn recover_original_context(&self) -> Result<Context> {
        let result_context = create_context()?;
        for graph in &self.graphs {
            let _result_graph =
                Self::recover_original_graph(graph.clone(), result_context.clone())?;
        }
        if let Some(id) = self.main_graph {
            let rebuilt_main_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                if id >= current_graphs.len() as u64 {
                    return Err(runtime_error!("Non-existent main graph"));
                }
                current_graphs[id as usize].clone()
            };
            result_context.set_main_graph(rebuilt_main_graph)?;
        }
        for (id, _) in &self.graphs_names {
            let current_graphs = &result_context.body.borrow().graphs;
            if *id >= current_graphs.len() as u64 {
                return Err(runtime_error!("graphs_names contain an invalid ID"));
            }
        }
        for ((graph_id, node_id), _) in &self.nodes_names {
            let current_graphs = &result_context.body.borrow().graphs;
            if *graph_id >= current_graphs.len() as u64 {
                return Err(runtime_error!("nodes_names contain an invalid graph ID"));
            }
            let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
            if *node_id >= current_nodes.len() as u64 {
                return Err(runtime_error!("nodes_names contain an invalid node ID"));
            }
        }
        for (id, name) in &self.graphs_names {
            let current_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                current_graphs[*id as usize].clone()
            };
            result_context.set_graph_name(current_graph, name)?;
        }
        for ((graph_id, node_id), name) in &self.nodes_names {
            let current_node = {
                let current_graphs = &result_context.body.borrow().graphs;
                let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
                current_nodes[*node_id as usize].clone()
            };
            result_context.set_node_name(current_node, name)?;
        }
        for (id, annotations) in &self.graphs_annotations {
            let current_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                current_graphs[*id as usize].clone()
            };
            for annotation in annotations {
                result_context.add_graph_annotation(&current_graph, annotation.clone())?;
            }
        }
        for ((graph_id, node_id), annotations) in &self.nodes_annotations {
            let current_node = {
                let current_graphs = &result_context.body.borrow().graphs;
                let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
                current_nodes[*node_id as usize].clone()
            };
            for annotation in annotations {
                result_context.add_node_annotation(&current_node, annotation.clone())?;
            }
        }
        if self.finalized {
            result_context.finalize()?;
        }
        Ok(result_context)
    }
}

type SerializableContext = Arc<SerializableContextBody>;

impl Clone for Context {
    /// Returns a new [Context] value with a copy of the pointer to a node.
    fn clone(&self) -> Self {
        Context {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Context {
    /// Tests whether `self` and `other` contexts are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Context] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Context {}

/// Public methods which supposed to be imported in Python.
#[cfg_attr(feature = "py-binding", impl_wrapper)]
impl Context {
    /// Creates an empty computation graph in this context.
    ///
    /// # Returns
    ///
    /// New computation graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// ```
    pub fn create_graph(&self) -> Result<Graph> {
        if self.body.borrow().finalized {
            return Err(runtime_error!("Can't add a graph to a finalized context"));
        }
        let id = self.body.borrow().graphs.len() as u64;
        let result = Graph {
            body: Arc::new(AtomicRefCell::new(GraphBody {
                finalized: false,
                nodes: vec![],
                output_node: None,
                id,
                context: self.downgrade(),
            })),
        };
        self.body.borrow_mut().graphs.push(result.clone());
        Ok(result)
    }

    /// Finalizes the context if all its graphs are finalized and the main graph is set.
    ///
    /// After finalization the context can't be changed.
    ///
    /// # Returns
    ///
    /// Finalized context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// c.set_main_graph(g).unwrap();
    /// c.finalize().unwrap();
    /// ```
    pub fn finalize(&self) -> Result<Context> {
        for graph in self.get_graphs() {
            graph.check_finalized()?;
        }
        let main_graph = self.body.borrow().main_graph.clone();
        match main_graph {
            Some(_) => {
                self.body.borrow_mut().finalized = true;
                Ok(self.clone())
            }
            _ => Err(runtime_error!(
                "Can't finalize the context without the main graph"
            )),
        }
    }

    /// Promotes a graph to the main one in this context.
    ///
    /// # Arguments
    ///
    /// `graph` - graph
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n = g.input(t).unwrap();
    /// n.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// c.set_main_graph(g).unwrap();
    /// ```
    pub fn set_main_graph(&self, graph: Graph) -> Result<Context> {
        let current_main_graph = self.body.borrow().main_graph.clone();
        match current_main_graph {
            Some(_) => Err(runtime_error!("Main graph is already set")),
            None => {
                if graph.get_context() != *self {
                    return Err(runtime_error!("Main graph is from the wrong context"));
                }
                graph.check_finalized()?;
                self.body.borrow_mut().main_graph = Some(graph.downgrade());
                Ok(self.clone())
            }
        }
    }

    /// Returns the vector of graphs contained in this context in order of creation.
    ///
    /// # Returns
    ///
    /// Vector of the graphs in this context
    pub fn get_graphs(&self) -> Vec<Graph> {
        self.body.borrow().graphs.clone()
    }

    /// Does nothing if the context is finalized; otherwise returns a runtime error.
    ///
    /// # Returns
    ///
    /// Runtime error if this context is not finalized
    pub fn check_finalized(&self) -> Result<()> {
        if !self.is_finalized() {
            return Err(runtime_error!("Context is not finalized"));
        }
        Ok(())
    }

    /// Returns the main graph of the context if it is already set.
    ///
    /// # Returns
    ///
    /// Main graph of the context
    pub fn get_main_graph(&self) -> Result<Graph> {
        match &self.body.borrow().main_graph {
            Some(g) => Ok(g.upgrade()),
            None => Err(runtime_error!("main graph is not set")),
        }
    }

    /// Returns the number of graphs contained in this context.
    ///
    /// # Returns
    ///
    /// Number of the graphs in this context
    pub fn get_num_graphs(&self) -> u64 {
        self.body.borrow().graphs.len() as u64
    }

    /// Returns the graph contained in this context with a given ID.
    ///
    /// A graph ID is a serial number of a graph between `0` and `n-1` where `n` is the number of graphs in this context.
    ///
    /// # Arguments
    ///
    /// `id` - ID of a graph
    ///
    /// # Returns
    ///
    /// Graph with the given ID
    pub fn get_graph_by_id(&self, id: u64) -> Result<Graph> {
        let graphs = &self.body.borrow().graphs;
        if id >= graphs.len() as u64 {
            Err(runtime_error!("Invalid id for the graph retrieval"))
        } else {
            Ok(graphs[id as usize].clone())
        }
    }

    /// Returns the node contained in this context with a given global ID.
    ///
    /// The global ID of a node is a pair of the node ID and the ID of its parent graph.
    ///
    /// # Arguments
    ///
    /// `id` - tuple (graph ID, node ID)
    ///
    /// # Returns
    ///
    /// Node with the given global ID
    pub fn get_node_by_global_id(&self, id: (u64, u64)) -> Result<Node> {
        self.get_graph_by_id(id.0)?.get_node_by_id(id.1)
    }

    /// Sets the name of a graph.
    ///
    /// A given name should be unique.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph
    /// * `name` - name of the graph
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// ```
    pub fn set_graph_name(&self, graph: Graph, name: &str) -> Result<Context> {
        if graph.get_context() != *self {
            return Err(runtime_error!(
                "The graph to be named is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a graph name in a finalized context"
            ));
        }
        let id = graph.get_id();
        let name_owned = name.to_owned();
        let mut cell = self.body.borrow_mut();
        if cell.graphs_names.get(&id).is_some() {
            return Err(runtime_error!("Can't set the graph name twice"));
        }
        if cell.graphs_names_inverse.get(name).is_some() {
            return Err(runtime_error!("Graph names must be unique"));
        }
        cell.graphs_names.insert(id, name_owned.clone());
        cell.graphs_names_inverse.insert(name_owned, id);
        Ok(self.clone())
    }

    /// Returns the name of a graph.
    ///
    /// # Arguments
    ///
    /// `graph` - graph
    ///
    /// # Returns
    ///
    /// Name of a given graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// assert_eq!(c.get_graph_name(g).unwrap(), "relu".to_owned());
    /// ```
    pub fn get_graph_name(&self, graph: Graph) -> Result<String> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let cell = self.body.borrow();
        Ok(cell
            .graphs_names
            .get(&graph.get_id())
            .ok_or_else(|| runtime_error!("The graph does not have a name assigned"))?
            .clone())
    }

    /// Returns the graph with a given name in this context.
    ///
    /// # Arguments
    ///
    /// `name` - graph name
    ///
    /// # Returns
    ///
    /// Graph with a given name
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// g.set_name("input_graph").unwrap();
    /// assert!(g == c.retrieve_graph("input_graph").unwrap());
    /// ```
    pub fn retrieve_graph(&self, name: &str) -> Result<Graph> {
        let cell = self.body.borrow();
        let id = cell
            .graphs_names_inverse
            .get(name)
            .ok_or_else(|| runtime_error!("No graph with such a name exists"))?;
        let graph = cell.graphs[*id as usize].clone();
        Ok(graph)
    }

    /// Sets the name of a node.
    ///
    /// A given name should be unique.
    ///
    /// # Arguments
    ///
    /// * `node` - node
    /// * `name` - name of a node
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// c.set_node_name(n, "XOR").unwrap();
    /// ```
    pub fn set_node_name(&self, node: Node, name: &str) -> Result<Context> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be named is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a node name in a finalized context"
            ));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let mut cell = self.body.borrow_mut();
        if cell.nodes_names.get(&(graph_id, node_id)).is_some() {
            return Err(runtime_error!("Can't set the node name twice"));
        }
        if cell.nodes_names_inverse.get(&graph_id).is_none() {
            cell.nodes_names_inverse.insert(graph_id, HashMap::new());
        }
        let graph_map_inverse = cell
            .nodes_names_inverse
            .get_mut(&graph_id)
            .expect("Should not be here!");
        if graph_map_inverse.get(name).is_some() {
            return Err(runtime_error!(
                "Node names must be unique (within the graph)"
            ));
        }
        graph_map_inverse.insert(name.to_owned(), node_id);
        cell.nodes_names
            .insert((graph_id, node_id), name.to_owned());
        Ok(self.clone())
    }

    /// Returns the name of a node.
    ///
    /// # Arguments
    ///
    /// `node` - node
    ///
    /// # Returns
    ///
    /// Name of a node or None if it doesn't have a name
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// assert_eq!(c.get_node_name(n).unwrap(), Some("XOR".to_owned()));
    /// ```
    pub fn get_node_name(&self, node: Node) -> Result<Option<String>> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!("The node is in a different context"));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let cell = self.body.borrow();
        Ok(cell.nodes_names.get(&(graph_id, node_id)).cloned())
    }

    /// Returns the node with a given name in a given graph.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph
    /// * `name` - node name
    ///
    /// # Returns
    ///
    /// Node with a given name
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// n.set_name("input_node").unwrap();
    /// assert!(n == c.retrieve_node(g, "input_node").unwrap());
    /// ```
    pub fn retrieve_node(&self, graph: Graph, name: &str) -> Result<Node> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let graph_id = graph.get_id();
        let cell = self.body.borrow();
        let node_id = cell
            .nodes_names_inverse
            .get(&graph_id)
            .ok_or_else(|| runtime_error!("The graph has no named nodes"))?
            .get(name)
            .ok_or_else(|| runtime_error!("Node with a given name does not exist"))?;
        Ok(graph.body.borrow().nodes[*node_id as usize].clone())
    }
    /// Check that two given contexts contain the same data, i.e. graphs, nodes, names, parameters.
    ///
    /// Underlying structures that contain pointers (graphs, nodes) are compared by data they refer to.
    ///
    /// # Arguments
    ///
    /// * `context2` - context to compare
    ///
    /// # Returns
    ///
    /// `true` if the given contexts contain the same content, otherwise `false`
    pub fn deep_equal(&self, context2: Context) -> bool {
        contexts_deep_equal(self.clone(), context2)
    }
}

fn serialize_hashmap<K, V>(map: HashMap<K, V>) -> Vec<(K, V)>
where
    K: Ord + Copy,
{
    let mut vec: Vec<_> = map.into_iter().collect();
    vec.sort_by_key(|(k, _)| *k);
    vec
}

/// Methods which aren't supposed to be imported in Python.
impl Context {
    pub(super) fn is_finalized(&self) -> bool {
        self.body.borrow().finalized
    }

    fn make_serializable(&self) -> SerializableContext {
        let main_graph = match self.get_main_graph() {
            Ok(g) => Some(g.get_id()),
            Err(_) => None,
        };
        let cell = self.body.borrow();
        Arc::new(SerializableContextBody {
            finalized: self.is_finalized(),
            graphs: self
                .get_graphs()
                .iter()
                .map(|g| g.make_serializable())
                .collect(),
            main_graph,
            graphs_names: serialize_hashmap(cell.graphs_names.clone()),
            nodes_names: serialize_hashmap(cell.nodes_names.clone()),
            graphs_annotations: serialize_hashmap(cell.graphs_annotations.clone()),
            nodes_annotations: serialize_hashmap(cell.nodes_annotations.clone()),
        })
    }

    fn add_type_checker(&self) -> Result<Context> {
        {
            let mut cell = self.body.borrow_mut();
            if cell.type_checker.is_some() {
                return Err(runtime_error!(
                    "Type checker associated with the context already exists"
                ));
            }
            cell.type_checker = Some(create_type_inference_worker(self.clone()));
        }
        for graph in self.get_graphs() {
            for node in graph.get_nodes() {
                node.get_type()?;
            }
        }
        Ok(self.clone())
    }

    fn get_total_size_nodes(&self) -> u64 {
        self.body.borrow().total_size_nodes
    }

    fn set_total_size_nodes(&self, size: u64) {
        self.body.borrow_mut().total_size_nodes = size;
    }

    fn try_update_total_size(&self, node: Node) -> Result<()> {
        let node_type = match node.get_operation() {
            Operation::Input(input_type) => input_type,
            Operation::Constant(t, _) => t,
            _ => return Ok(()),
        };
        if !node_type.is_valid() {
            return Err(runtime_error!("Node with an invalid type: {:?}", node_type));
        }
        let new_total_size = self
            .get_total_size_nodes()
            .checked_add(get_size_estimation_in_bits(node_type)?)
            .ok_or_else(|| runtime_error!("add overflow!"))?;
        if new_total_size > type_size_limit_constants::MAX_TOTAL_SIZE_NODES {
            return Err(runtime_error!(
                "Can't add a node: total size of nodes exceeds MAX_TOTAL_SIZE_NODES"
            ));
        }
        self.set_total_size_nodes(new_total_size);
        Ok(())
    }

    fn unregister_node(&self, node: Node) -> Result<()> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be unregister from  a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't unregister a node from  a finalized context"
            ));
        }

        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();

        let mut cell = self.body.borrow_mut();
        let name_option = cell.nodes_names.remove(&(graph_id, node_id));
        cell.nodes_annotations.remove(&(graph_id, node_id));
        if cell.nodes_names_inverse.get(&graph_id).is_none() {
            return Ok(());
        }
        let graph_map_inverse = cell
            .nodes_names_inverse
            .get_mut(&graph_id)
            .expect("Should not be here!");
        if let Some(name) = name_option {
            graph_map_inverse.remove(&name);
        }
        Ok(())
    }

    fn to_versioned_data(&self) -> Result<VersionedData> {
        VersionedData::create_versioned_data(
            DATA_VERSION,
            serde_json::to_string(&self.make_serializable())?,
        )
    }
    fn prepare_input_values<T: Clone>(
        &self,
        graph: Graph,
        values: HashMap<&str, T>,
    ) -> Result<Vec<T>> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let graph_id = graph.get_id();
        let cell = self.body.borrow();
        for node_name in values.keys() {
            cell.nodes_names_inverse
                .get(&graph_id)
                .ok_or_else(|| runtime_error!("Trying to call graph without named nodes"))?
                .get(node_name as &str)
                .ok_or_else(|| runtime_error!("Input with a given name is not found"))?;
        }
        let mut result = vec![];
        for node in graph.get_nodes() {
            if node.get_operation().is_input() {
                let node_id = node.get_id();
                let node_name = cell
                    .nodes_names
                    .get(&(graph_id, node_id))
                    .ok_or_else(|| runtime_error!("Unnamed input"))?;
                let node_value = values
                    .get(node_name as &str)
                    .ok_or_else(|| runtime_error!("Unspecified input"))?
                    .clone();
                result.push(node_value);
            }
        }
        Ok(result)
    }

    pub(super) fn add_node_annotation(
        &self,
        node: &Node,
        annotation: NodeAnnotation,
    ) -> Result<Context> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be annotated is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't add a node annotation in a finalized context"
            ));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let key = (graph_id, node_id);
        let mut cell = self.body.borrow_mut();
        let annotations = cell.nodes_annotations.get_mut(&key);
        if let Some(annotation_vec) = annotations {
            annotation_vec.push(annotation);
        } else {
            cell.nodes_annotations.insert(key, vec![annotation]);
        }
        Ok(self.clone())
    }

    pub(super) fn get_node_annotations(&self, node: Node) -> Result<Vec<NodeAnnotation>> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!("The node is in a different context"));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let cell = self.body.borrow();
        Ok(cell
            .nodes_annotations
            .get(&(graph_id, node_id))
            .cloned()
            .unwrap_or_default())
    }

    fn add_graph_annotation(&self, graph: &Graph, annotation: GraphAnnotation) -> Result<Context> {
        if graph.get_context() != *self {
            return Err(runtime_error!(
                "The graph to be annotated is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a graph annotation in a finalized context"
            ));
        }
        let id = graph.get_id();
        let mut cell = self.body.borrow_mut();
        let annotations = cell.graphs_annotations.get_mut(&id);
        if let Some(annotation_vec) = annotations {
            annotation_vec.push(annotation);
        } else {
            cell.graphs_annotations.insert(id, vec![annotation]);
        }
        Ok(self.clone())
    }

    fn get_graph_annotations(&self, graph: Graph) -> Result<Vec<GraphAnnotation>> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let cell = self.body.borrow();
        Ok(cell
            .graphs_annotations
            .get(&graph.get_id())
            .cloned()
            .unwrap_or_default())
    }

    pub(super) fn downgrade(&self) -> WeakContext {
        WeakContext {
            body: Arc::downgrade(&self.body),
        }
    }
}

impl Serialize for Context {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let versioned_context = self
            .to_versioned_data()
            .expect("Error during conversion from Context into VersionedData");
        //VersionedData::from(self.clone());
        versioned_context.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Context {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Context, D::Error>
    where
        D: Deserializer<'de>,
    {
        let versioned_context = VersionedData::deserialize(deserializer)?;
        if !versioned_context.check_version(DATA_VERSION) {
            Err(runtime_error!(
                "Context version doesn't match the requirement"
            ))
            .map_err(serde::de::Error::custom)
        } else {
            let serializable_context =
                serde_json::from_str::<SerializableContext>(versioned_context.get_data_string())
                    .expect("Error during deserialization of SerializableContext");
            serializable_context
                .recover_original_context()
                .map_err(serde::de::Error::custom)
        }
    }
}

/// In general, `create_unchecked_context()` should not return errors, but
/// we still make the result type Result<Context> for uniformity.
pub(super) fn create_unchecked_context() -> Result<Context> {
    Ok(Context {
        body: Arc::new(AtomicRefCell::new(ContextBody {
            finalized: false,
            graphs: vec![],
            main_graph: None,
            graphs_names: HashMap::new(),
            graphs_names_inverse: HashMap::new(),
            nodes_names: HashMap::new(),
            nodes_names_inverse: HashMap::new(),
            graphs_annotations: HashMap::new(),
            nodes_annotations: HashMap::new(),
            type_checker: None,
            total_size_nodes: 0,
        })),
    })
}

/// Creates an empty computation context.
///
/// # Returns
///
/// New computation context
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// let c = create_context().unwrap();
/// ```
#[cfg_attr(feature = "py-binding", fn_wrapper)]
pub fn create_context() -> Result<Context> {
    let context = create_unchecked_context()?;
    context.add_type_checker()?;
    Ok(context)
}

fn graphs_deep_equal(graph1: Graph, graph2: Graph) -> bool {
    let graph1_body = graph1.body.borrow();
    let graph2_body = graph2.body.borrow();
    if graph1_body.finalized != graph2_body.finalized {
        return false;
    }
    if graph1_body.nodes.len() != graph2_body.nodes.len() {
        return false;
    }
    for j in 0..graph1_body.nodes.len() {
        let node1 = graph1_body.nodes[j].clone();
        let node2 = graph2_body.nodes[j].clone();
        let node1_body = node1.body.borrow();
        let node2_body = node2.body.borrow();
        if node1_body.operation != node2_body.operation {
            return false;
        }
        let node_dependencies1: Vec<u64> = node1_body
            .node_dependencies
            .iter()
            .map(|n| n.upgrade().get_id())
            .collect();
        let node_dependencies2: Vec<u64> = node2_body
            .node_dependencies
            .iter()
            .map(|n| n.upgrade().get_id())
            .collect();
        if node_dependencies1 != node_dependencies2 {
            return false;
        }
        let graph_dependencies1: Vec<u64> = node1_body
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade().get_id())
            .collect();
        let graph_dependencies2: Vec<u64> = node2_body
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade().get_id())
            .collect();
        if graph_dependencies1 != graph_dependencies2 {
            return false;
        }
    }
    if graph1_body
        .output_node
        .clone()
        .map(|n| n.upgrade().get_id())
        != graph2_body
            .output_node
            .clone()
            .map(|n| n.upgrade().get_id())
    {
        return false;
    }
    true
}

/// Check that two given contexts contain the same data, i.e. graphs, nodes, names, parameters.
///
/// Underlying structures that contain pointers (graphs, nodes) are compared by data they refer to.
///
/// # Arguments
///
/// * `context1` - first context to compare
/// * `context2` - second context to compare
///
/// # Returns
///
/// `true` if the given contexts contain the same content, otherwise `false`
pub fn contexts_deep_equal(context1: Context, context2: Context) -> bool {
    let body1 = context1.body.borrow();
    let body2 = context2.body.borrow();
    if body1.finalized != body2.finalized {
        return false;
    }
    if body1.graphs_names != body2.graphs_names {
        return false;
    }
    if body1.nodes_names != body2.nodes_names {
        return false;
    }
    if body1.nodes_annotations != body2.nodes_annotations {
        return false;
    }
    if body1.graphs_annotations != body2.graphs_annotations {
        return false;
    }
    if body1.graphs.len() != body2.graphs.len() {
        return false;
    }
    for i in 0..body1.graphs.len() {
        if !graphs_deep_equal(body1.graphs[i].clone(), body2.graphs[i].clone()) {
            return false;
        }
    }
    body1.main_graph.clone().map(|g| g.upgrade().get_id())
        == body2.main_graph.clone().map(|g| g.upgrade().get_id())
}

// Pass the node name of `in_node` to `out_node` if it is present.
pub(crate) fn copy_node_name(in_node: Node, out_node: Node) -> Result<()> {
    if let Some(node_name) = in_node.get_name()? {
        out_node.set_name(&node_name)?;
    }
    Ok(())
}

type WeakContextBodyPointer = Weak<AtomicRefCell<ContextBody>>;

pub(super) struct WeakContext {
    body: WeakContextBodyPointer,
}

impl WeakContext {
    //upgrade function panics if the the Context pointer it downgraded from went out of scope
    pub(super) fn upgrade(&self) -> Context {
        Context {
            body: self.body.upgrade().unwrap(),
        }
    }
}

#[doc(hidden)]
#[cfg(feature = "py-binding")]
#[pyo3::pymethods]
impl PyBindingSliceElement {
    #[staticmethod]
    pub fn from_single_element(ind: i64) -> Self {
        PyBindingSliceElement {
            inner: SliceElement::SingleIndex(ind),
        }
    }
    #[staticmethod]
    pub fn from_sub_array(start: Option<i64>, end: Option<i64>, step: Option<i64>) -> Self {
        PyBindingSliceElement {
            inner: SliceElement::SubArray(start, end, step),
        }
    }
    #[staticmethod]
    pub fn from_ellipsis() -> Self {
        PyBindingSliceElement {
            inner: SliceElement::Ellipsis,
        }
    }
}

pub mod util {
    use super::{create_context, Context, Graph, Node};
    use crate::errors::Result;

    /// Creates a computation context with a single graph within it.
    ///
    /// The graph is passed to the provided `build_graph_fn` function to
    /// specify the computation. The node returned by the function is marked
    /// as output.
    ///
    /// # Returns
    ///
    /// New computation context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::util::simple_context;
    /// # use ciphercore_base::data_types::{scalar_type, INT32};
    /// let c = simple_context(|g| {
    ///     let a = g.input(scalar_type(INT32))?;
    ///     let b = g.input(scalar_type(INT32))?;
    ///     g.add(a, b)
    /// }).unwrap();
    /// ```
    pub fn simple_context<F>(build_graph_fn: F) -> Result<Context>
    where
        F: FnOnce(&Graph) -> Result<Node>,
    {
        let c = create_context()?;
        let g = c.create_graph()?;
        let out = build_graph_fn(&g)?;
        out.set_as_output()?;
        g.finalize()?;
        g.set_as_main()?;
        c.finalize()?;
        Ok(c)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_types::{
        array_type, scalar_type, tuple_type, vector_type, BIT, UINT16, UINT64,
    };
    use crate::inline::inline_ops::InlineConfig;
    use crate::mpc::mpc_compiler::{prepare_for_mpc_evaluation, IOStatus};
    use crate::version::DATA_VERSION;
    use std::panic;
    use std::rc::Rc;

    #[test]
    fn test_wellformed_cases() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(BIT)).unwrap();
        let input2 = graph.input(scalar_type(BIT)).unwrap();
        graph.add(input1.clone(), input2.clone()).unwrap();
        graph.subtract(input1.clone(), input2.clone()).unwrap();
        graph.multiply(input1.clone(), input2.clone()).unwrap();
        graph.dot(input1.clone(), input2.clone()).unwrap();
        graph.matmul(input1.clone(), input2.clone()).unwrap();
        graph.truncate(input1.clone(), 123).unwrap();
        let input3 = graph.input(array_type(vec![10, 20, 30], BIT)).unwrap();
        graph.sum(input3.clone(), vec![1, 2]).unwrap();
        graph.permute_axes(input3.clone(), vec![1, 2, 0]).unwrap();
        graph.get(input3.clone(), vec![1, 2]).unwrap();
        graph
            .reshape(input3.clone(), array_type(vec![20, 300], BIT))
            .unwrap();
        graph.nop(input3.clone()).unwrap();
        let key = graph.random(array_type(vec![128], BIT)).unwrap();
        graph
            .prf(key.clone(), 0, array_type(vec![10, 10], UINT64))
            .unwrap();
        graph
            .stack(vec![input1.clone(), input2.clone()], vec![2, 1])
            .unwrap();
        let c = graph
            .constant(scalar_type(BIT), Value::from_bytes(vec![1]))
            .unwrap();
        let input4 = graph.input(array_type(vec![10, 10], UINT64)).unwrap();
        let bits = graph.a2b(input4.clone()).unwrap();
        graph.b2a(bits.clone(), UINT64).unwrap();
        let t = graph
            .create_tuple(vec![input1.clone(), input2.clone()])
            .unwrap();
        let _v = graph
            .create_vector(scalar_type(BIT), vec![input1.clone(), input2.clone()])
            .unwrap();
        let nt = graph
            .create_named_tuple(vec![
                ("Name".to_owned(), input1.clone()),
                ("Gender".to_owned(), input2.clone()),
            ])
            .unwrap();
        graph.tuple_get(t, 1).unwrap();
        graph.named_tuple_get(nt, "Gender".to_owned()).unwrap();
        let v = graph.repeat(c.clone(), 100).unwrap();
        graph.zip(vec![v.clone(), v.clone(), v.clone()]).unwrap();
        let zero = graph
            .constant(scalar_type(UINT64), Value::from_bytes(vec![0; 8]))
            .unwrap();
        graph.vector_get(v, zero).unwrap();
        graph.array_to_vector(input1.clone()).unwrap();
        graph.vector_to_array(input1.clone()).unwrap();
    }

    #[test]
    fn call_iterate_test() {
        let context = create_unchecked_context().unwrap();
        let single_bit_adder = context.create_graph().unwrap();
        {
            let carry = single_bit_adder.input(scalar_type(BIT)).unwrap();
            let inputs = single_bit_adder
                .input(tuple_type(vec![scalar_type(BIT), scalar_type(BIT)]))
                .unwrap();
            let a = single_bit_adder.tuple_get(inputs.clone(), 0).unwrap();
            let b = single_bit_adder.tuple_get(inputs.clone(), 1).unwrap();
            let ac = single_bit_adder.add(carry.clone(), a.clone()).unwrap();
            let bc = single_bit_adder.add(carry.clone(), b.clone()).unwrap();
            let result = single_bit_adder.add(ac.clone(), b.clone()).unwrap();
            let result_carry = single_bit_adder
                .add(
                    single_bit_adder.multiply(ac.clone(), bc.clone()).unwrap(),
                    carry,
                )
                .unwrap();
            let output = single_bit_adder
                .create_tuple(vec![result_carry.clone(), result.clone()])
                .unwrap();
            single_bit_adder.set_output_node(output).unwrap();
            single_bit_adder.finalize().unwrap();
        }
        let v32 = vector_type(32, scalar_type(BIT));
        let adder = context.create_graph().unwrap();
        {
            let a = adder.input(v32.clone()).unwrap();
            let b = adder.input(v32.clone()).unwrap();
            let azb = adder.zip(vec![a, b]).unwrap();
            let c = adder
                .constant(scalar_type(BIT), Value::from_bytes(vec![0]))
                .unwrap();
            let cr = adder.iterate(single_bit_adder, c, azb).unwrap();
            let r = adder.tuple_get(cr, 1).unwrap();
            adder.set_output_node(r).unwrap();
            adder.finalize().unwrap();
        }
        let three_adder = context.create_graph().unwrap();
        let a = three_adder.input(v32.clone()).unwrap();
        let b = three_adder.input(v32.clone()).unwrap();
        let c = three_adder.input(v32.clone()).unwrap();
        let result = three_adder
            .call(
                adder.clone(),
                vec![three_adder.call(adder.clone(), vec![a, b]).unwrap(), c],
            )
            .unwrap();
        three_adder.set_output_node(result).unwrap();
        three_adder.finalize().unwrap();
        context.set_main_graph(three_adder).unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_malformed_graphs() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let graph2 = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(UINT64)).unwrap();
        let input2 = graph2.input(scalar_type(UINT64)).unwrap();
        let e1 = graph.add(input1.clone(), input2.clone());
        assert!(e1.is_err());
        let fake_node = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: graph.downgrade(),
                node_dependencies: vec![],
                graph_dependencies: vec![],
                operation: Operation::Input(scalar_type(BIT)),
                id: 0,
            })),
        };
        let e2 = graph.add(fake_node.clone(), input1.clone());
        assert!(e2.is_err());
        let fake_node_2 = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: graph.downgrade(),
                node_dependencies: vec![],
                graph_dependencies: vec![],
                operation: Operation::Input(scalar_type(BIT)),
                id: 31337,
            })),
        };
        let e3 = graph.add(fake_node_2.clone(), input1.clone());
        assert!(e3.is_err());
        graph.set_output_node(input1.clone()).unwrap();
        graph.finalize().unwrap();
        let e4 = graph.add(input1.clone(), input1.clone());
        assert!(e4.is_err());
        let graph3 = context.create_graph().unwrap();
        let e5 = graph3.finalize();
        assert!(e5.is_err());
        let e6 = graph3.set_output_node(input1);
        assert!(e6.is_err());
    }

    #[test]
    fn test_malformed_contexts() {
        let context = create_unchecked_context().unwrap();
        let e1 = context.finalize();
        assert!(e1.is_err());
        let graph = context.create_graph().unwrap();
        let e2 = graph.finalize();
        assert!(e2.is_err());
        graph
            .set_output_node(graph.create_tuple(vec![]).unwrap())
            .unwrap();
        let e4 = context.set_main_graph(graph.clone());
        assert!(e4.is_err());
        graph.finalize().unwrap();
        let e3 = context.finalize();
        assert!(e3.is_err());
        context.set_main_graph(graph.clone()).unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_malformed_call_iterate() {
        let context1 = create_unchecked_context().unwrap();
        let graph1 = context1.create_graph().unwrap();
        let output = graph1.create_tuple(vec![]).unwrap();
        graph1.set_output_node(output).unwrap();
        let graph2 = context1.create_graph().unwrap();
        let e1 = graph2.call(graph1.clone(), vec![]);
        assert!(e1.is_err());
        graph1.finalize().unwrap();
        graph2.call(graph1.clone(), vec![]).unwrap();
        let context2 = create_unchecked_context().unwrap();
        let graph3 = context2.create_graph().unwrap();
        let e2 = graph3.call(graph1.clone(), vec![]);
        assert!(e2.is_err());
        let graph4 = context1.create_graph().unwrap();
        graph4.input(tuple_type(vec![])).unwrap();
        graph4.input(tuple_type(vec![])).unwrap();
        let t = graph4.create_tuple(vec![]).unwrap();
        let tt = graph4.create_tuple(vec![t.clone(), t.clone()]).unwrap();
        graph4.set_output_node(tt).unwrap();
        let graph5 = context1.create_graph().unwrap();
        let es = graph5.create_tuple(vec![]).unwrap();
        let v = graph5
            .repeat(graph5.create_tuple(vec![]).unwrap(), 10)
            .unwrap();
        let e3 = graph5.iterate(graph4.clone(), es.clone(), v.clone());
        assert!(e3.is_err());
        graph4.finalize().unwrap();
        graph5
            .iterate(graph4.clone(), es.clone(), v.clone())
            .unwrap();
        let graph6 = context2.create_graph().unwrap();
        let es = graph6.create_tuple(vec![]).unwrap();
        let v = graph6
            .repeat(graph6.create_tuple(vec![]).unwrap(), 10)
            .unwrap();
        let e4 = graph6.iterate(graph4.clone(), es.clone(), v.clone());
        assert!(e4.is_err());
    }

    #[test]
    fn test_graph_consistency() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(BIT)).unwrap();
        let input2 = graph.input(scalar_type(BIT)).unwrap();
        graph.add(input1.clone(), input2.clone()).unwrap();
        graph.set_output_node(input1.clone()).unwrap();
        graph.finalize().unwrap();
        for (i, node) in graph.get_nodes().iter().enumerate() {
            assert_eq!(node.get_id(), i as u64);
            assert!(graph == node.get_graph());
            for dependency in node.get_node_dependencies() {
                assert!(dependency.get_id() < node.get_id());
            }
        }
        let operations: Vec<Operation> = graph
            .get_nodes()
            .iter()
            .map(|x| x.get_operation())
            .collect();
        assert!(operations.len() == 3);
        if !operations[0].is_input() {
            panic!("Input expected");
        }
        if !operations[1].is_input() {
            panic!("Input expected");
        }
        match operations[2] {
            Operation::Add => {}
            _ => {
                panic!("Add expected");
            }
        }
    }

    #[test]
    fn test_unfinalized_graphs() {
        let context = create_unchecked_context().unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let graph = context.create_graph().unwrap();
        let graph2 = context.create_graph().unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let i = graph2.input(scalar_type(BIT)).unwrap();
        graph2.set_output_node(i).unwrap();
        graph2.finalize().unwrap();
        context.set_main_graph(graph2).unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let ii = graph.input(scalar_type(BIT)).unwrap();
        graph.set_output_node(ii).unwrap();
        graph.finalize().unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_operation_serialization() {
        let o = Operation::Constant(scalar_type(BIT), Value::from_bytes(vec![1]));
        let se = serde_json::to_string(&o).unwrap();
        assert_eq!(
            se,
            format!("{{\"Constant\":[{{\"Scalar\":\"bit\"}},{{\"version\":{},\"data\":\"{{\\\"body\\\":{{\\\"Bytes\\\":[1]}}}}\"}}]}}", DATA_VERSION)
        );
        let de = serde_json::from_str::<Operation>(&se).unwrap();
        assert_eq!(de, o);
    }

    fn context_generators() -> Vec<Box<dyn Fn() -> Context>> {
        let context1 = || {
            let context = create_unchecked_context().unwrap();
            context
        };
        let context2 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph).unwrap();
            context.finalize().unwrap();
            context
        };
        let context3 = || {
            let context = create_unchecked_context().unwrap();
            context.create_graph().unwrap();
            context
        };
        let context4 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context
        };
        let context5 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            graph.input(scalar_type(BIT)).unwrap();
            context
        };
        let context6 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            graph
                .constant(scalar_type(BIT), Value::from_bytes(vec![1]))
                .unwrap();
            context
        };
        let context7 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i1 = graph.input(scalar_type(BIT)).unwrap();
            let i2 = graph.input(scalar_type(BIT)).unwrap();
            graph.add(i1, i2).unwrap();
            context
        };
        let context8 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i1 = graph.input(scalar_type(BIT)).unwrap();
            let i2 = graph.input(scalar_type(BIT)).unwrap();
            graph.add(i2, i1).unwrap();
            context
        };
        let context9 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            graph3.call(graph1, vec![i]).unwrap();
            context
        };
        let context10 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            graph3.call(graph2, vec![i]).unwrap();
            context
        };
        let context11 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            let o = graph3.call(graph2, vec![i]).unwrap();
            graph3.set_output_node(o).unwrap();
            context
        };
        let context12 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph).unwrap();
            context
        };
        let context13 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph.clone()).unwrap();
            context.set_graph_name(graph, "main").unwrap();
            context.finalize().unwrap();
            context
        };
        let context14 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i.clone()).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph.clone()).unwrap();
            context.set_graph_name(graph.clone(), "main").unwrap();
            context.set_node_name(i.clone(), "input").unwrap();
            context
                .add_graph_annotation(&graph, GraphAnnotation::AssociativeOperation)
                .unwrap();
            context
                .add_node_annotation(&i, NodeAnnotation::AssociativeOperation)
                .unwrap();
            context.finalize().unwrap();
            context
        };
        let context15 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let mut x = graph.input(scalar_type(BIT)).unwrap();
            for i in 1..20 {
                let y = graph.input(scalar_type(BIT)).unwrap();
                y.set_name(format!("input_{}", i).as_str()).unwrap();
                x = graph.add(x, y).unwrap();
            }
            graph.set_output_node(x).unwrap();
            graph.finalize().unwrap();
            context
        };
        let mut closures: Vec<Box<dyn Fn() -> Context>> = vec![];
        closures.push(Box::new(context1));
        closures.push(Box::new(context2));
        closures.push(Box::new(context3));
        closures.push(Box::new(context4));
        closures.push(Box::new(context5));
        closures.push(Box::new(context6));
        closures.push(Box::new(context7));
        closures.push(Box::new(context8));
        closures.push(Box::new(context9));
        closures.push(Box::new(context10));
        closures.push(Box::new(context11));
        closures.push(Box::new(context12));
        closures.push(Box::new(context13));
        closures.push(Box::new(context14));
        closures.push(Box::new(context15));
        closures
    }

    fn test_context_deep_equal_helper_equal<F>(f: F)
    where
        F: Fn() -> Context,
    {
        let context1 = f();
        let context2 = f();
        assert!(context1 != context2);
        assert!(contexts_deep_equal(context1, context2));
    }

    fn test_context_deep_equal_helper_nonequal<F1, F2>(f1: F1, f2: F2)
    where
        F1: Fn() -> Context,
        F2: Fn() -> Context,
    {
        let context1 = f1();
        let context2 = f2();
        assert!(context1 != context2);
        assert!(!contexts_deep_equal(context1, context2));
    }

    #[test]
    fn test_context_deep_equal() {
        let generators = context_generators();
        for i in 0..generators.len() {
            test_context_deep_equal_helper_equal(&generators[i]);
            for j in 0..i {
                test_context_deep_equal_helper_nonequal(&generators[i], &generators[j]);
            }
        }
    }

    pub fn deserialize_error_lenient(serialized_string: &str, error_msg: &str) {
        use std::panic::catch_unwind;
        panic::set_hook(Box::new(|_info| {
            // See: https://stackoverflow.com/questions/35559267/suppress-panic-output-in-rust-when-using-paniccatch-unwind
        }));
        let result = catch_unwind(|| serde_json::from_str::<Context>(serialized_string).unwrap());
        // This is a (nasty) hack.
        // We check whether the returned error contain the expected error message.
        use ciphercore_utils::execute_main::extract_panic_message;
        if let Err(e) = result {
            match extract_panic_message(e) {
                Some(msg) => {
                    if !msg.contains(error_msg) {
                        panic!("Undesirable panic: {}", msg);
                    }
                }
                None => panic!("Panic of unknown type"),
            }
        } else {
            panic!("Expected error not occur")
        }
    }

    use std::{
        fs::File,
        io::{prelude::*, BufReader},
        path::Path,
    };

    fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
        let file = File::open(filename).expect("no such file");
        let buf = BufReader::new(file);
        buf.lines()
            .map(|l| l.expect("Could not parse line"))
            .collect()
    }

    #[test]
    fn test_context_serialize() {
        let generators = context_generators();
        let contexts: Vec<Context> = generators.iter().map(|generator| generator()).collect();
        let serialized_contexts: Vec<String> = contexts
            .iter()
            .map(|context| serde_json::to_string(context).unwrap())
            .collect();
        let deserialized_contexts: Vec<Context> = serialized_contexts
            .iter()
            .map(|serialized_context| serde_json::from_str(serialized_context).unwrap())
            .collect();
        assert_eq!(contexts.len(), deserialized_contexts.len());
        for i in 0..contexts.len() {
            assert!(contexts[i] != deserialized_contexts[i]);
            assert!(contexts_deep_equal(
                contexts[i].clone(),
                deserialized_contexts[i].clone()
            ));
            assert_eq!(
                serialized_contexts[i],
                serde_json::to_string(&deserialized_contexts[i]).unwrap()
            )
        }

        //Read test cases from golden file
        let test_case = lines_from_file("./src/test_data/version_testcase.txt");
        assert_eq!(serde_json::to_string(&contexts[0]).unwrap(), test_case[0]);

        //Following test case expect an error message "Non-existent main graph" which is caused by the field "\"main_graph\":918276318"
        deserialize_error_lenient(&test_case[1], "Non-existent main graph");
        assert_eq!(serde_json::to_string(&contexts[9]).unwrap(), test_case[2]);
        //Following test case expect an error message "Non-existent node dependency" which is caused by the field "\"node_dependencies\":[918723]"
        deserialize_error_lenient(&test_case[3], "Non-existent node dependency");
        //Following test case expect an error message "Non-existent graph dependency" which is caused by the field "\"graph_dependencies\":[918723]"
        deserialize_error_lenient(&test_case[4], "Non-existent graph dependency");
        assert_eq!(serde_json::to_string(&contexts[13]).unwrap(), test_case[5]);
        //Following test case expect an error message "Non-existent output node" which is caused by the field "\"output_node\":9817273"
        deserialize_error_lenient(&test_case[6], "Non-existent output node");
        //Following test case expect an error message "graphs_names contain an invalid ID" which is caused by the field "\"graphs_names\":[[8079123,\"main\"]]"
        deserialize_error_lenient(&test_case[7], "graphs_names contain an invalid ID");
        //Following test case expect an error message "nodes_names contain an invalid graph ID" which is caused by the field "\"nodes_names\":[[[8079123,0],\"input\"]]"
        deserialize_error_lenient(&test_case[8], "nodes_names contain an invalid graph ID");
        //Following test case expect an error message "nodes_names contain an invalid graph ID" which is caused by the field "\"nodes_names\":[[[0,8079123],\"input\"]]"
        deserialize_error_lenient(&test_case[9], "nodes_names contain an invalid node ID");
        //Following test case expect an error message "Context version doesn't match the requirement" which is caused by its old version number
        deserialize_error_lenient(
            &test_case[10],
            "Context version doesn't match the requirement",
        );
        //Following test case expect an error message "Context version doesn't match the requirement" which is caused by its old version number. Although its payload is unsupported, this should not cause any error before passing the version check.
        deserialize_error_lenient(
            &test_case[11],
            "Context version doesn't match the requirement",
        );
    }

    use crate::data_types::INT32;
    use crate::data_values::Value;
    use crate::evaluators::random_evaluate;
    use std::iter::FromIterator;

    #[test]
    fn test_named_contexts() {
        let helper = || -> Result<Context> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input_a = graph.input(scalar_type(INT32))?;
            let input_b = graph.input(scalar_type(INT32))?;
            let output = graph.add(input_a.clone(), input_b.clone())?;
            graph.set_output_node(output.clone())?;
            graph.finalize()?;
            context.set_main_graph(graph.clone())?;
            assert!(context.get_graph_name(graph.clone()).is_err());
            assert!(context.retrieve_graph("main").is_err());
            assert!(context.get_node_name(input_a.clone())?.is_none());
            assert!(context.retrieve_node(graph.clone(), "a").is_err());
            context.set_graph_name(graph.clone(), "main")?;
            context.set_node_name(input_a.clone(), "a")?;
            assert!(context.retrieve_node(graph.clone(), "b").is_err());
            context.set_node_name(input_b.clone(), "b")?;
            context.finalize()?;
            assert_eq!(context.get_graph_name(graph.clone())?, "main");
            assert_eq!(
                context.get_node_name(input_a.clone())?,
                Some("a".to_owned())
            );
            assert_eq!(
                context.get_node_name(input_b.clone())?,
                Some("b".to_owned())
            );
            assert!(context.retrieve_node(graph.clone(), "a")? == input_a.clone());
            Ok(context)
        };
        let context = helper().unwrap();
        let helper2 = |context: Context| -> Result<i32> {
            let other_context = create_context()?;
            let other_graph = other_context.create_graph()?;
            let input = other_graph.input(scalar_type(BIT))?;
            let other_input = other_graph.input(scalar_type(BIT))?;
            assert!(context
                .prepare_input_values::<Value>(other_graph.clone(), HashMap::new())
                .is_err());
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("a", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            other_context.set_node_name(input, "b")?;
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("a", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("b", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            other_context.set_node_name(other_input, "c")?;
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph,
                    HashMap::from_iter([("b", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            let g = context.retrieve_graph("main")?;
            let result = random_evaluate(
                g.clone(),
                context.prepare_input_values(
                    g.clone(),
                    HashMap::from_iter([
                        ("a", Value::from_scalar(123, INT32)?),
                        ("b", Value::from_scalar(456, INT32)?),
                    ]),
                )?,
            )?;
            let result = result.to_i32(INT32)?;
            Ok(result)
        };
        assert_eq!(helper2(context).unwrap(), 579);
        let helper3 = |context: Context| -> Result<()> {
            let other_context = create_context()?;
            let other_graph = other_context.create_graph()?;
            let other_node = other_graph.input(scalar_type(BIT))?;
            assert!(context
                .set_graph_name(other_graph.clone(), "outside")
                .is_err());
            assert!(context.get_graph_name(other_graph.clone()).is_err());
            assert!(context
                .set_node_name(other_node.clone(), "outside")
                .is_err());
            assert!(context.get_node_name(other_node.clone()).is_err());
            assert!(context.retrieve_node(other_graph.clone(), "a").is_err());
            Ok(())
        };
        helper3(helper().unwrap()).unwrap();
        let helper4 = || -> Result<()> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input = graph.input(scalar_type(BIT))?;
            graph.set_output_node(input.clone())?;
            graph.finalize()?;
            context.set_main_graph(graph.clone())?;
            context.finalize()?;
            assert!(context.set_graph_name(graph, "main").is_err());
            assert!(context.set_node_name(input, "input").is_err());
            Ok(())
        };
        helper4().unwrap();
        let helper5 = || -> Result<()> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input = graph.input(scalar_type(BIT))?;
            let other_graph = context.create_graph()?;
            let other_input = graph.input(scalar_type(BIT))?;
            context.set_graph_name(graph.clone(), "main")?;
            assert!(context.set_graph_name(graph, "main3").is_err());
            assert!(context.set_graph_name(other_graph, "main").is_err());
            context.set_node_name(input.clone(), "input")?;
            assert!(context.set_node_name(input, "input3").is_err());
            assert!(context.set_node_name(other_input, "input").is_err());
            Ok(())
        };
        helper5().unwrap();
    }

    #[test]
    fn test_context_type_checking() {
        || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?;
            let i = g.input(tuple_type(vec![]))?;
            assert!(g.add(i.clone(), i.clone()).is_err());
            // Now checking that the node actually have not gotten added by accident
            assert_eq!(g.get_nodes().len(), 1);
            Ok(())
        }()
        .unwrap();
    }

    fn generate_pair_of_equal_contexts() -> Vec<(Context, Context)> {
        let context1 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            g.set_output_node(i)?;
            g.finalize()?;
            g.set_as_main()?;
            Ok(context)
        }()
        .unwrap();
        let context2 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            i.set_as_output()?;
            g.finalize()?;
            context.set_main_graph(g)?;
            Ok(context)
        }()
        .unwrap();
        let context3 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            context.set_graph_name(g, "random graph name")?;
            Ok(context)
        }()
        .unwrap();
        let context4 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            context.create_graph()?.set_name("random graph name")?;
            Ok(context)
        }()
        .unwrap();
        let context5 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            context.set_node_name(i, "random node name")?;
            Ok(context)
        }()
        .unwrap();
        let context6 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?
                .set_name("random node name")?;
            Ok(context)
        }()
        .unwrap();
        let context7 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i1 = g.input(scalar_type(BIT))?;
            let i2 = g.input(scalar_type(BIT))?;
            g.add(i1.clone(), i2.clone())?;
            g.subtract(i1.clone(), i2.clone())?;
            g.multiply(i1.clone(), i2.clone())?;
            g.dot(i1.clone(), i2.clone())?;
            g.matmul(i1.clone(), i2.clone())?;
            g.truncate(i1.clone(), 123)?;
            g.sum(i1.clone(), vec![1, 4, 7])?;
            g.permute_axes(i1.clone(), vec![1, 4, 7])?;
            g.get(i1.clone(), vec![1, 4])?;
            g.reshape(i1.clone(), array_type(vec![12, 34], BIT))?;
            g.nop(i1.clone())?;
            g.prf(i1.clone(), 123, scalar_type(BIT))?;
            g.a2b(i1.clone())?;
            g.b2a(i1.clone(), BIT)?;
            g.tuple_get(i1.clone(), 0)?;
            g.named_tuple_get(i1.clone(), "field name".to_owned())?;
            g.vector_get(i1.clone(), i2)?;
            g.array_to_vector(i1.clone())?;
            g.vector_to_array(i1.clone())?;
            g.repeat(i1.clone(), 123)?;
            Ok(context)
        }()
        .unwrap();
        let context8 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i1 = g.input(scalar_type(BIT))?;
            let i2 = g.input(scalar_type(BIT))?;
            i1.add(i2.clone())?;
            i1.subtract(i2.clone())?;
            i1.multiply(i2.clone())?;
            i1.dot(i2.clone())?;
            i1.matmul(i2.clone())?;
            i1.truncate(123)?;
            i1.sum(vec![1, 4, 7])?;
            i1.permute_axes(vec![1, 4, 7])?;
            i1.get(vec![1, 4])?;
            i1.reshape(array_type(vec![12, 34], BIT))?;
            i1.nop()?;
            i1.prf(123, scalar_type(BIT))?;
            i1.a2b()?;
            i1.b2a(BIT)?;
            i1.tuple_get(0)?;
            i1.named_tuple_get("field name".to_owned())?;
            i1.vector_get(i2)?;
            i1.array_to_vector()?;
            i1.vector_to_array()?;
            i1.repeat(123)?;
            Ok(context)
        }()
        .unwrap();
        let result = vec![
            (context1, context2),
            (context3, context4),
            (context5, context6),
            (context7, context8),
        ];
        result
    }

    #[test]
    fn test_node_graph_helpers() {
        let pairs_of_contexts = generate_pair_of_equal_contexts();
        for (context1, context2) in pairs_of_contexts {
            assert!(contexts_deep_equal(context1, context2));
        }
        || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?.set_name("graph name")?;
            let i = g.input(scalar_type(BIT))?.set_name("node name")?;
            assert_eq!(g.get_name()?, "graph name");
            assert!(g.retrieve_node("node name")? == i);
            assert_eq!(i.get_name()?, Some("node name".to_owned()));
            assert_eq!(
                g.prepare_input_values(hashmap!("node name" => Value::from_scalar(1, BIT)?))?,
                vec![Value::from_scalar(1, BIT)?]
            );
            Ok(())
        }()
        .unwrap();
    }

    #[test]
    fn test_operation_fmt_display() {
        let test_operation_fmt_display_helper = || -> Result<()> {
            let o0 = Rc::new(Operation::Input(scalar_type(UINT16)));
            assert_eq!(format!("{}", o0), "Input");
            let o1 = Rc::new(Operation::Add);
            assert_eq!(format!("{}", o1), "Add");
            let o2 = Rc::new(Operation::Truncate(10));
            assert_eq!(format!("{}", o2), "Truncate");
            let o3 = Rc::new(Operation::Get(vec![10, 20]));
            assert_eq!(format!("{}", o3), "Get");
            let o4 = Rc::new(Operation::NOP);
            assert_eq!(format!("{}", o4), "NOP");
            let o5 = Rc::new(Operation::CreateNamedTuple(vec![
                "Name".to_string(),
                "Address".to_string(),
            ]));
            assert_eq!(format!("{}", o5), "CreateNamedTuple");
            let o6 = Rc::new(Operation::NamedTupleGet("Name".to_string()));
            assert_eq!(format!("{}", o6), "NamedTupleGet");
            Ok(())
        };
        test_operation_fmt_display_helper().unwrap();
    }

    #[test]
    fn test_annotations() {
        let test_annotations_helper = || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?;
            let i = g.input(scalar_type(BIT))?;
            g.add_annotation(GraphAnnotation::AssociativeOperation)?;
            i.add_annotation(NodeAnnotation::AssociativeOperation)?;
            assert_eq!(
                g.get_annotations()?,
                vec![GraphAnnotation::AssociativeOperation]
            );
            assert_eq!(
                i.get_annotations()?,
                vec![NodeAnnotation::AssociativeOperation]
            );
            Ok(())
        };
        test_annotations_helper().unwrap();
    }

    async fn parallel_get_type(output: Node) -> Result<Type> {
        output.get_type()
    }

    async fn parallel_random_evaluate(graph: Graph, context: Context) -> Result<Value> {
        random_evaluate(
            graph.clone(),
            context.prepare_input_values(
                graph,
                HashMap::from_iter([
                    ("one", Value::from_scalar(123, INT32)?),
                    ("two", Value::from_scalar(456, INT32)?),
                ]),
            )?,
        )
    }

    async fn parallel_prepare_for_mpc_evaluation(
        context: Context,
        input_party_map: Vec<Vec<IOStatus>>,
        output_parties: Vec<Vec<IOStatus>>,
        inline_config: InlineConfig,
    ) -> Result<Context> {
        prepare_for_mpc_evaluation(context, input_party_map, output_parties, inline_config)
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 50)]
    async fn test_parallel_after_finalize() -> Result<()> {
        let context = create_context()?;
        let graph = context.create_graph()?;
        let input1 = graph.input(scalar_type(INT32))?;
        let input2 = graph.input(scalar_type(INT32))?;
        let output = graph.add(input1.clone(), input2.clone())?;
        graph.set_output_node(output.clone())?;
        graph.finalize()?;
        context.set_main_graph(graph.clone())?;

        context.set_node_name(input1.clone(), "one")?;
        context.set_node_name(input2.clone(), "two")?;

        context.finalize()?;

        assert!(output.clone().get_type().is_ok());

        const PAR_ITERS: usize = 2001;

        let mut get_type_futures = vec![];
        for _ in 0..PAR_ITERS {
            get_type_futures.push(parallel_get_type(output.clone()));
        }
        futures::future::try_join_all(get_type_futures).await?;

        let mut get_random_evaluate_futures = vec![];
        for _ in 0..PAR_ITERS {
            get_random_evaluate_futures
                .push(parallel_random_evaluate(graph.clone(), context.clone()))
        }
        futures::future::try_join_all(get_random_evaluate_futures).await?;

        let input_parties = vec![IOStatus::Party(0), IOStatus::Party(1)];
        let output_parties = vec![IOStatus::Party(0)];

        let mut get_mpc_eval_futures = vec![];
        for _ in 0..PAR_ITERS {
            get_mpc_eval_futures.push(parallel_prepare_for_mpc_evaluation(
                context.clone(),
                vec![input_parties.clone()],
                vec![output_parties.clone()],
                InlineConfig::default(),
            ));
        }
        futures::future::try_join_all(get_mpc_eval_futures).await?;

        Ok(())
    }
}