package owl-base

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file owl_base_dense_ndarray_generic.ml

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
# 1 "src/base/dense/owl_base_dense_ndarray_generic.ml"
(*
 * OWL - OCaml Scientific and Engineering Computing
 * Copyright (c) 2016-2019 Liang Wang <liang.wang@cl.cam.ac.uk>
 *)

[@@@warning "-32"]

open Bigarray

open Owl_types

type ('a, 'b) t = ('a, 'b, c_layout) Genarray.t

type ('a, 'b) kind = ('a, 'b) Bigarray.kind

module Scalar = Owl_base_maths


(* Prepend an array with ones to the given length *)
let _prepend_dims dims desired_len =
  let dims_len = Array.length dims in
  if dims_len >= desired_len then dims
  else (Array.append (Array.make (desired_len - dims_len) 1) dims)


let _get_broadcasted_dims dims_a dims_b =
  let len_c = Stdlib.max (Array.length dims_a) (Array.length dims_b) in
  let ext_dims_a = _prepend_dims dims_a len_c in
  let ext_dims_b = _prepend_dims dims_b len_c in
  let dims_c = Array.make len_c 0 in

  for i = 0 to len_c - 1 do
    let val_a = ext_dims_a.(i) in
    let val_b = ext_dims_b.(i) in
    if val_a = val_b then
      dims_c.(i) <- val_a
    else
      if val_a != 1 && val_b != 1
      then raise (Invalid_argument "The arrays cannot be broadcast into the same shape")
      else dims_c.(i) <- (Stdlib.max val_a val_b)
  done;
  (ext_dims_a, ext_dims_b, dims_c)


(* Increment the index array, with respect to the dimensions array *)
let _next_index ind dims =
  let num_dims = Array.length ind in
  let p = ref (num_dims - 1) in
  let ok = ref false in
  while !p >= 0 && not !ok do
    if ind.(!p) + 1 < dims.(!p) then (
      ind.(!p) <- (ind.(!p) + 1);
      ok := true;
    )
    else (
      ind.(!p) <- 0;
      p := !p - 1;
    )
  done;
  !ok


let _get_broadcasted_index ind dims =
  let num_dims = Array.length dims in
  let calc_fun =
    (fun i ->
       let max_ind = dims.(i) in
       let ind_val = ind.(i) in
       if ind_val < max_ind
       then ind_val
       else (
         if max_ind = 1
         then 0
         else raise (Invalid_argument "not broadcasted correctly")
       )
    ) in
  (Array.init num_dims calc_fun)


let _apply_perm arr perm =
  Array.init (Array.length arr) (fun i -> arr.(perm.(i)))


let _draw_int_samples replacement range count =
  if not replacement && count > range then
    raise (Invalid_argument "cannot draw that many samples from the given range, without replacement")
  else (
    let pop_cnt = ref range in
    let pop = Array.init !pop_cnt (fun i -> i) in
    let rand_gen = Random.State.make_self_init() in
    let draw_fun = (fun _ ->
        let index = Random.State.int rand_gen !pop_cnt in
        let sample = pop.(index) in
        if replacement then
          sample
        else (
          pop_cnt := !pop_cnt - 1;
          pop.(index) <- pop.(!pop_cnt); (* eliminate sample by swapping with last element *)
          sample
        )
      )
    in
    Array.init count draw_fun
  )


let _enumerate_slice_def dim ?(step) start stop =
  let start = if start < 0 then dim + start else start in
  let stop = if stop < 0 then dim + stop else stop in
  let step = match step with
    | Some x -> x
    | None   -> if (start <= stop) then 1 else -1
  in
  assert (((start <= stop) && (step > 0)) || ((start > stop) && (step < 0)));
  let step_abs = Stdlib.abs step in
  let len = ((Stdlib.abs (stop - start)) + step_abs) / step_abs in
  (Array.init len (fun i -> start + i * step))


(* Rewrite the indices s.t. for each dimension they are a list of explicit indices *)
let _expand_slice_indices index_list dims =
  let rank = Array.length dims in
  let sdef_len = List.length index_list in (* the number of dimensions this slice specifies *)
  let _expand_slice_index = (
    fun i ind -> match ind with
      | []                  -> Array.init dims.(i) (fun i -> i)
      | [start]             -> _enumerate_slice_def dims.(i) start start
      | [start; stop]       -> _enumerate_slice_def dims.(i) start stop
      | [start; stop; step] -> _enumerate_slice_def dims.(i) ~step:step start stop
      | x                   -> Array.of_list x
  ) in
  Array.append
    (Array.of_list (List.mapi _expand_slice_index index_list)) (* for the axis where the index was specified *)
    (Array.init (rank - sdef_len) (* the rest of the axis is just all of them *)
       (fun p -> Array.init dims.(p + sdef_len) (fun i -> i)))


let reset x =
  let _kind = Genarray.kind x in
  Genarray.fill x (Owl_const.zero _kind)


let empty kind dims = Genarray.create kind c_layout dims


let create kind dims value =
  let x = empty kind dims in
  Genarray.fill x value;
  x


let create_ ~out a = Genarray.fill out a


let zeros kind dims = create kind dims (Owl_const.zero kind)


let zeros_ ~out = reset out


let ones kind dims = create kind dims (Owl_const.one kind)


let ones_ ~out = Genarray.(fill out (Owl_const.one (kind out)))


let shape x = Genarray.dims x


let nth_dim x i = Genarray.nth_dim x i


let num_dims x = Array.length (shape x)


let numel x = Owl_utils.numel x


let kind x = Genarray.kind x


let get x index = (Genarray.get x index)


let set x index value = (Genarray.set x index value)


let eye kind n =
  let m = zeros kind [|n; n|] in
  for i = 0 to n - 1 do
    set m [|i; i|] (Owl_const.one kind)
  done;
  m


(*TODO: optimise, test *)
let get_slice index_list varr =
  let dims = shape varr in
  let rank = Array.length dims in
  let index_array = _expand_slice_indices index_list dims in
  let slice_dims = Array.map (fun a -> Array.length a) index_array in
  let slice_varr = empty (kind varr) slice_dims in
  let slice_ind = Array.make rank 0 in
  let original_ind = Array.make rank 0 in
  let should_stop = ref false in
  while not !should_stop do
    for i = 0 to rank - 1 do
      original_ind.(i) <- (index_array.(i)).(slice_ind.(i))
    done;
    Genarray.set slice_varr slice_ind (Genarray.get varr original_ind);
    if not (_next_index slice_ind slice_dims) then
      should_stop := true
  done;
  slice_varr


(*TODO: optimise, test *)
let set_slice index_list varr slice_varr =
  let dims = shape varr in
  let rank = Array.length dims in
  let index_array = _expand_slice_indices index_list dims in
  let slice_dims = Array.map (fun a -> Array.length a) index_array in
  let slice_varr = reshape slice_varr slice_dims in
  let slice_ind = Array.make rank 0 in
  let original_ind = Array.make rank 0 in
  let should_stop = ref false in
  while not !should_stop do
    for i = 0 to rank - 1 do
      original_ind.(i) <- (index_array.(i)).(slice_ind.(i))
    done;
    Genarray.set varr original_ind (Genarray.get slice_varr slice_ind);
    if not (_next_index slice_ind slice_dims) then
      should_stop := true
  done


(* The result shares the underlying buffer with original, not a copy *)
let reshape x d =
  let minus_one = Owl_utils.Array.count d (-1) in
  assert (minus_one <= 1);
  if minus_one = 0 then reshape x d
  else (
    let n = numel x in
    let m = Array.fold_right ( * ) d (-1) in
    let e = Array.map (fun a -> if a = -1 then n / m else a) d in
    reshape x e
  )


(* Return the array as a contiguous block, without copying *)
let flatten x = reshape x [|(numel x)|]


let fill x a = Genarray.fill x a


let copy x =
  let y = empty (kind x) (shape x) in
  Genarray.blit x y;
  y


let copy_ ~out x =
  let src = flatten x in
  let dst = flatten out in
  Genarray.blit src dst


let reshape_ ~out x =
  if not (x == out) then
    copy_ ~out x


let reverse x =
  let n = numel x in
  let y = empty (kind x) (shape x) in
  let y_flat = reshape y [|n|] in
  let x_flat = reshape x [|n|] in
  for i = 0 to n - 1 do
    set y_flat [|i|] (get x_flat [|n - 1 - i|])
  done;
  y


let reverse_ ~out x =
  let n = numel x in
  let y_flat = reshape out [|n|] in
  let x_flat = reshape x [|n|] in
  for i = 0 to n - 1 do
    set y_flat [|i|] (get x_flat [|n - 1 - i|])
  done


let map_ f x =
  let y = flatten x |> array1_of_genarray in
  let length = numel x in
  for i = 0 to length - 1 do
    (Array1.unsafe_set y i (f (Array1.unsafe_get y i)))
  done


let mapi_ f x =
  let y = flatten x |> array1_of_genarray in
  let length = numel x in
  for i = 0 to length - 1 do
    (Array1.unsafe_set y i (f i (Array1.unsafe_get y i)))
  done


let init kind dims f =
  let varr = empty kind dims in
  let varr_flat = flatten varr |> array1_of_genarray in
  let n = numel varr in
  for i = 0 to n - 1 do
    Array1.unsafe_set varr_flat i (f i)
  done;
  varr


let init_nd k d f =
  let x = empty k d in
  let y = array1_of_genarray (flatten x) in
  let n = numel x in
  let s = Owl_utils.calc_stride d in
  let j = Array.copy s in
  for i = 0 to n - 1 do
    Owl_utils.index_1d_nd i j s;
    Array1.unsafe_set y i (f j)
  done;
  x


(* Map a NDarray from elements x -> f(x), by copying the array *)
let map f x =
  let y = copy x in
  map_ f y;
  y


let mapi f x =
  let y = copy x in
  let y' = flatten y |> array1_of_genarray in
  for i = 0 to (Array1.dim y') - 1 do
    let a = Array1.unsafe_get y' i in
    Array1.unsafe_set y' i (f i a)
  done;
  y

let strides x = x |> shape |> Owl_utils.calc_stride


let slice_size x = x |> shape |> Owl_utils.calc_slice


(* TODO: performance can be optimised by removing embedded loops *)
(* generic fold funtion *)
let foldi ?axis f a x =
  let x' = flatten x |> array1_of_genarray in
  match axis with
  | Some axis -> (
      let m, n, o, s = Owl_utils.reduce_params axis x in
      let start_x = ref 0 in
      let start_y = ref 0 in
      let incy = ref 0 in
      let k = ref 0 in

      let y = create (kind x) s a in
      let y' = flatten y |> array1_of_genarray in

      for _i = 0 to m - 1 do
        for j = 0 to n - 1 do
          let b = Array1.unsafe_get y' (!start_y + !incy) in
          let c = Array1.unsafe_get x' (!start_x + j) in
          Array1.unsafe_set y' (!start_y + !incy) (f !k b c);
          if !incy + 1 = o then incy := 0
          else incy := !incy + 1;
          k := !k + 1;
        done;
        start_x := !start_x + n;
        start_y := !start_y + o;
      done;
      y
    )
  | None   -> (
      let b = ref a in
      for i = 0 to (numel x) - 1 do
        let c = Array1.unsafe_get x' i in
        b := f i !b c
      done;
      create (kind x) [|1|] !b
    )


let fold ?axis f a x = foldi ?axis (fun _ b c ->  f b c) a x


(* generic scan function *)
let scani ?axis f x =
  let d = num_dims x in
  let a = match axis with
    | Some a -> a
    | None   -> d - 1
  in
  assert (0 <= a && a < d);

  let _stride = strides x in
  let _slicez = slice_size x in
  let m = (numel x) / _slicez.(a) in
  let n = _slicez.(a) - _stride.(a) in
  let incx = _slicez.(a) in
  let incy = _slicez.(a) in
  let start_x = ref 0 in
  let start_y = ref _stride.(a) in
  let k = ref 0 in

  let y = copy x in
  let y' = flatten y |> array1_of_genarray in

  for _i = 0 to m - 1 do
    for j = 0 to n - 1 do
      let b = Array1.unsafe_get y' (!start_x + j) in
      let c = Array1.unsafe_get y' (!start_y + j) in
      Array1.unsafe_set y' (!start_y + j) (f !k b c);
      k := !k + 1
    done;
    start_x := !start_x + incx;
    start_y := !start_y + incy;
  done;
  y


let scan ?axis f x = scani ?axis (fun _ a b -> f a b) x


let iteri f x =
  let x' = flatten x |> array1_of_genarray in
  for i = 0 to (Array1.dim x') - 1 do
    let a = Array1.unsafe_get x' i in
    f i a
  done


let iter f x =
  let x' = flatten x |> array1_of_genarray in
  for i = 0 to (Array1.dim x') - 1 do
    let a = Array1.unsafe_get x' i in
    f a
  done


let filteri f x =
  let s = Owl_utils.Stack.make () in
  iteri (fun i y ->
      if f i y = true then
        Owl_utils.Stack.push s i
    ) x;
  Owl_utils.Stack.to_array s


let filter f x = filteri (fun _ y -> f y) x


let sequential_ ?a ?step ~out =
  let k = kind out in
  let a = match a with
    | Some a -> a
    | None   -> Owl_const.zero k
  in
  let step = match step with
    | Some step -> step
    | None      -> Owl_const.one k
  in
  let _add = Owl_base_dense_common._add_elt k in
  let _mul = Owl_base_dense_common._mul_elt k in
  let _flt = Owl_base_dense_common._float_typ_elt k in
  mapi_ (fun i _ ->
    _add a (_mul (_flt (float_of_int i)) step)
  ) out


let sequential k ?a ?step dimension =
  let x = empty k dimension in
  sequential_ ?a ?step ~out:x;
  x


let of_array kind arr dims =
  let varr = empty kind dims in
  let flat_varr = flatten varr |> array1_of_genarray in
  let n = numel varr in
  for i = 0 to n - 1 do
    Array1.unsafe_set flat_varr i arr.(i)
  done;
  varr


let uniform k ?a ?b dims =
  let a = match a with Some a -> a | None -> Owl_const.zero k in
  let b = match b with Some b -> b | None -> Owl_const.one k in
  let uniform_fun = Owl_base_dense_common._uniform_elt k a b in
  let x = empty k dims in
  map_ uniform_fun x;
  x


let uniform_ ?a ?b ~out =
  let k = kind out in
  let a = match a with Some a -> a | None -> Owl_const.zero k in
  let b = match b with Some b -> b | None -> Owl_const.one k in
  let uniform_fun = Owl_base_dense_common._uniform_elt k a b in
  map_ uniform_fun out


let bernoulli k ?(p=0.5) dims =
  let bernoulli_fun = fun _ ->
    let a = Owl_base_stats.bernoulli_rvs ~p in
    Owl_base_dense_common._float_typ_elt k a
  in
  let x = empty k dims in
  map_ bernoulli_fun x;
  x


let bernoulli_ ?(p=0.5) ~out =
  let k = kind out in
  let bernoulli_fun = fun _ ->
    let a = Owl_base_stats.bernoulli_rvs ~p in
    Owl_base_dense_common._float_typ_elt k a
  in
  map_ bernoulli_fun out


let gaussian k ?mu ?sigma dims =
  let mu = match mu with Some a -> a | None -> Owl_const.zero k in
  let sigma = match sigma with Some a -> a | None -> Owl_const.one k in
  let gaussian_fun = Owl_base_dense_common._gaussian_elt k mu sigma in
  let x = empty k dims in
  map_ gaussian_fun x;
  x


let gaussian_ ?mu ?sigma ~out =
  let k = kind out in
  let mu = match mu with Some a -> a | None -> Owl_const.zero k in
  let sigma = match sigma with Some a -> a | None -> Owl_const.one k in
  let gaussian_fun = Owl_base_dense_common._gaussian_elt k mu sigma in
  map_ gaussian_fun out


let print ?max_row ?max_col ?header ?fmt x =
  let dims = shape x in
  let rank = Array.length dims in
  let n = dims.(rank - 1) in
  let max_row = match max_row with
    | Some a -> Some a
    | None   -> Some ((numel x) / n)
  in
  let max_col = match max_col with
    | Some a -> Some a
    | None   -> Some n
  in
  Owl_pretty.print_dsnda ?max_row ?max_col ?header ?elt_to_str_fun:fmt x


(* TODO: optimise *)
let tile varr reps =
  (* First ensure len(reps) = num_dims(varr) *)
  let dims = shape varr in
  let result_rank = Stdlib.max (Array.length dims) (Array.length reps) in
  let dims = _prepend_dims dims result_rank in
  let reps = _prepend_dims reps result_rank in
  let varr = reshape varr dims in
  (* now len(reps) = num_dims(varr) *)
  let result_dims = Array.map2 (fun a b -> a * b) dims reps in
  let result_varr = empty (kind varr) result_dims in
  let result_ind = Array.make result_rank 0 in
  let original_ind = Array.make result_rank 0 in
  let should_stop = ref false in

  while not !should_stop do
    for i = 0 to result_rank - 1 do
      original_ind.(i) <- (Stdlib.(mod) result_ind.(i) dims.(i))
    done;
    Genarray.set result_varr result_ind (Genarray.get varr original_ind);
    if not (_next_index result_ind result_dims) then
      should_stop := true
  done;
  result_varr


(* TODO: optimise *)
let split ?(axis=0) parts varr =
  let dims = shape varr in
  let rank = Array.length dims in
  let pos = ref 0 in
  let axis_indices = Array.map (fun d -> (pos := !pos + d; [!pos - d; !pos - 1])) parts in
  let slices_defs =
    Array.map (fun ind ->
        Array.to_list (Array.init rank
                         (fun i -> if i = axis then ind else [])))
      axis_indices
  in
  (Array.map (fun def -> get_slice def varr) slices_defs)

let squeeze ?(axis=[||]) x =
  let a = match Array.length axis with
    | 0 -> Array.init (num_dims x) (fun i -> i)
    | _ -> axis
  in
  let s = Owl_utils.Array.filteri (fun i v ->
    not (v == 1 && Array.mem i a)
  ) (shape x)
  in
  reshape x s

let expand ?(hi=false) x d =
  let d0 = d - (num_dims x) in
  match d0 > 0 with
  | true  -> (
      if hi = true then
        Owl_utils.Array.pad `Right 1 d0 (shape x) |> reshape x
      else
        Owl_utils.Array.pad `Left 1 d0 (shape x) |> reshape x
    )
  | false -> x

(* TODO : ensure this is desired behaviour *)
(* Similar to draw rows for matrices *)
let draw ?(axis=0) varr count =
  let dims = shape varr in
  let rank = Array.length dims in
  let indices = _draw_int_samples false dims.(axis) count in
  (get_slice
     (List.init rank
        (fun i -> if i = axis then (Array.to_list indices) else []))
     varr,
   indices)


let _expand_padding_index d s =
  let ls = Array.length s in
  let ld = Array.length d in
  let d  = Owl_utils.Array.pad `Right [|0;0|] (ls - ld) d in
  Array.map (function
    | [||]  -> [|0;0|]
    | [|x|] -> [|x;x|]
    | x     -> x
  ) d


let rec _copy_to_padding p1 ls l0 l1 i0 i1 d0 d1 s0 s1 x0 x1 =
  if d0 < d1 then (
    for i = 0 to s0.(d0) - 1 do
      i0.(d0) <- i;
      i1.(d0) <- i + p1.(d0).(0);
      _copy_to_padding p1 ls l0 l1 i0 i1 (d0 + 1) d1 s0 s1 x0 x1;
      i0.(d0) <- 0;
      i1.(d0) <- p1.(d0).(0);
    done
  )
  else (
    let j0 = Owl_utils.index_nd_1d i0 l0 in
    let j1 = Owl_utils.index_nd_1d i1 l1 in
    let subx = Genarray.sub_left x0 j0 ls.(d0) in
    let suby = Genarray.sub_left x1 j1 ls.(d0) in
    Genarray.blit subx suby
  )


let _highest_padding_dimension p =
  let l = Array.length p - 1 in
  let d = ref l in
  (try for i = l downto 0 do
    d := i;
    if p.(i) <> [|0;0|] then failwith "pad:highest_padding_dimension"
  done with _exn -> ());
  !d


let pad ?v d x =
  let k = kind x in
  let v = match v with
    | Some v -> v
    | None   -> Owl_const.zero k
  in
  let s0 = shape x in
  let x' = flatten x in
  let p1 = _expand_padding_index (Owl_utils.llss2aarr d) s0 in
  let s1 = Array.map2 (fun m n -> m + n.(0) + n.(1)) s0 p1 in
  let s' = Owl_utils_array.fold_right ( * ) s1 1 in
  let y' = create k [|s'|] v in
  let ls = Owl_utils.calc_slice s0 in
  let l0 = Owl_utils.calc_stride s0 in
  let l1 = Owl_utils.calc_stride s1 in
  let i0 = Array.make (num_dims x) 0 in
  let i1 = Array.map (fun a -> a.(0)) p1 in
  let d0 = 0 in
  let d1 = _highest_padding_dimension p1 in
  _copy_to_padding p1 ls l0 l1 i0 i1 d0 d1 s0 s1 x' y';
  reshape y' s1


(* TODO: optimise? *)
let concatenate ?(axis=0) varrs =
  let varrs_num = Array.length varrs in
  (* dimensions of all NDarrays *)
  let all_dims = Array.map shape varrs in
  (* the dimensions before the axis *)
  let prefix_dims = Array.sub all_dims.(0) 0 axis in
  (* the sum of the dimensions of each NDarray along given axis *)
  let sum_axis_dims = Array.fold_left (fun x a -> x + a.(axis)) 0 all_dims in
  (* the dimensions after the axis *)
  let suffix_dims = Array.sub all_dims.(0)
      (axis + 1) ((Array.length all_dims.(0)) - axis - 1)
  in
  let result_dims =
    Array.concat [prefix_dims; [|sum_axis_dims|]; suffix_dims]
  in
  let result_varr = empty (kind varrs.(0)) result_dims in
  let prefix_dims_product = Array.fold_left ( * ) 1 prefix_dims in
  let suffix_dims_product = Array.fold_left ( * ) 1 suffix_dims in
  let reshaper_fun = (
    (* Reshape the variable as [prefix_dims_product, rest] *)
    fun varr ->
      let old_shape = shape varr in
      let new_shape =
        [|prefix_dims_product; old_shape.(axis) * suffix_dims_product|]
      in
      reshape varr new_shape
  ) in
  let reshaped_result = reshaper_fun result_varr in
  let reshaped_varrs = Array.map reshaper_fun varrs in
  begin
    for i = 0 to prefix_dims_product - 1 do
      let start_index = ref 0 in
      let result_slice = Genarray.slice_left reshaped_result [|i|] in
      for j = 0 to varrs_num - 1 do
        let src_slice = Genarray.slice_left reshaped_varrs.(j) [|i|] in
        let block_len = all_dims.(j).(axis) * suffix_dims_product in
        let result_sub =
          Genarray.sub_left result_slice !start_index block_len in
        Genarray.blit src_slice result_sub;
        start_index := !start_index + block_len
      done
    done;
    result_varr
  end


(* TODO: is there a more efficient way to do copy? *)
let repeat x reps =
  (* check the validity of reps *)
  if Array.exists ((>) 1) reps then
    failwith "repeat: repetition must be >= 1";
  let x_dims = num_dims x in
  assert (Array.length reps = x_dims);

  if (Array.for_all ((=) 1) reps) = true then
    copy x
  else (
    let _kind = kind x in
    let x' = flatten x in
    let x_shape = shape x in
    let y_shape = Array.map2 ( * ) x_shape reps in
    let num = Owl_utils_array.fold_right ( * ) y_shape 1 in
    let y' = empty _kind [|num|] in

    if x_dims = 1 then (
      let ofsy = ref 0 in
      for i = 0 to numel x - 1 do
        let elemx = get x' [|i|] in
        for _j = 0 to reps.(0) - 1 do
          set y' [|!ofsy|] elemx;
          ofsy := !ofsy + 1
        done
      done
    )
    else (
      let highest_dim = x_dims - 1 in
      let slice_x  = Owl_utils.calc_slice x_shape in
      let stride_y = Owl_utils.calc_stride y_shape in

      let hd = ref (highest_dim + 1) in
      while !hd > 1 && reps.(!hd - 1) = 1 do
        hd := !hd - 1;
      done;
      let hd = if !hd = highest_dim + 1 then highest_dim else !hd in

      (* Copy the HD dimension from x to y *)

      let block_num = Array.make hd 0 in
      for i = 0 to hd - 1 do
        block_num.(i) <- slice_x.(i) / slice_x.(hd);
      done;
      let counter = Array.make hd 0 in

      let ofsx = ref 0 in
      let ofsy = ref 0 in
      let block_sz = reps.(hd) in

      for _i = 0 to block_num.(0) - 1 do
        let ofsy_sub = ref !ofsy in
        if block_sz = 1 then (
          let subx = Genarray.sub_left x' !ofsx slice_x.(hd) in
          let suby = Genarray.sub_left y' !ofsy_sub slice_x.(hd) in
          Genarray.blit subx suby
        )
        else (
          for j = 0 to slice_x.(hd) - 1 do
            let elemx = get x' [|!ofsx + j|] in
            for k = 0 to block_sz - 1 do
              set y' [|!ofsy_sub + k|] elemx
            done;
            ofsy_sub := !ofsy_sub + block_sz
          done
        );
        ofsx := !ofsx + slice_x.(hd);
        ofsy := !ofsy + stride_y.(hd - 1) * reps.(hd - 1);
        for j = hd - 1 downto 1 do
          let c = counter.(j) in
          if c + 1 = block_num.(j) then (
            ofsy := !ofsy + stride_y.(j - 1) * (reps.(j - 1) - 1);
          );
          counter.(j) <- if c + 1 = block_num.(j) then 0 else c + 1
        done
      done;

      (* Copy the lower dimensions within y *)

      for d = hd - 1 downto 0 do
        let block_num = Array.make (d + 1) 0 in
        for i = 0 to d do
          block_num.(i) <- slice_x.(i) / slice_x.(d + 1);
        done;
        let ofsy = ref 0 in
        let block_sz = stride_y.(d) in
        let counter = Array.make hd 0 in

        for _i = 0 to block_num.(0) - 1 do
          let ofsy_sub = ref (!ofsy + block_sz) in
          for _j = 1 to reps.(d) - 1 do
            let subx = Genarray.sub_left y' !ofsy block_sz in
            let suby = Genarray.sub_left y' !ofsy_sub block_sz in
            Genarray.blit subx suby;
            ofsy_sub := !ofsy_sub + block_sz
          done;

          ofsy := !ofsy + stride_y.(d) * reps.(d);
          for j = d - 1 downto 0 do
            let c = counter.(j) in
            if c + 1 = block_num.(j + 1) then (
              ofsy := !ofsy + stride_y.(j) * (reps.(j) - 1);
            );
            counter.(j) <- if c + 1 = block_num.(j + 1) then 0 else c + 1
          done
        done
      done
    );
    reshape y' y_shape
  )


(* mathematical functions *)

let abs x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._abs_elt _kind in
  map _func x


let abs_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._abs_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let conj x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._conj_elt _kind in
  map _func x


let conj_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._conj_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map _func out


let neg x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._neg_elt _kind in
  map _func x


let neg_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._neg_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let reci x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._inv_elt _kind in
  map _func x


let reci_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._inv_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let floor x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._floor_elt _kind in
  map _func x


let floor_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._floor_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let ceil x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._ceil_elt _kind in
  map _func x


let ceil_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._ceil_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let round x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._round_elt _kind in
  map _func x


let round_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._round_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let trunc x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._trunc_elt _kind in
  map _func x


let trunc_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._trunc_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let fix x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._fix_elt _kind in
  map _func x


let fix_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._fix_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let erf _x = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.erf")


let erf_ ?_out _x = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.erf_")


let erfc _x = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.erfc")


let erfc_ ?_out _x = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.erfc_")


let sqr x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sqr_elt _kind in
  map _func x


let sqr_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sqr_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let sqrt x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sqrt_elt _kind in
  map _func x


let sqrt_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sqrt_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let cbrt x =
  let _kind = kind x in
  let b = Owl_base_dense_common._float_typ_elt _kind (1. /. 3.) in
  let _func = fun a -> Owl_base_dense_common._pow_elt _kind a b in
  map _func x


let cbrt_ ?out x =
  let _kind = kind x in
  let b = Owl_base_dense_common._float_typ_elt _kind (1. /. 3.) in
  let _func = fun a -> Owl_base_dense_common._pow_elt _kind a b in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let log x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log_elt _kind in
  map _func x


let log_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.log out


let log2 x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log2_elt _kind in
  map _func x


let log2_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log2_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let log10 x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log10_elt _kind in
  map _func x


let log10_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log10_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let log1p x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log1p_elt _kind in
  map _func x


let log1p_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._log1p_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let exp x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp_elt _kind in
  map _func x


let exp_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let exp2 x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp2_elt _kind in
  map _func x


let exp2_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp2_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let exp10 x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp10_elt _kind in
  map _func x


let exp10_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._exp10_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let expm1 x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._expm1_elt _kind in
  map _func x


let expm1_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._expm1_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let sin x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sin_elt _kind in
  map _func x


let sin_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sin_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let cos x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._cos_elt _kind in
  map _func x


let cos_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._cos_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let tan x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._tan_elt _kind in
  map _func x


let tan_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._tan_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let sinh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sinh_elt _kind in
  map _func x


let sinh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._sinh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let cosh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._cosh_elt _kind in
  map _func x


let cosh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._cosh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let tanh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._tanh_elt _kind in
  map _func x


let tanh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._tanh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let asin x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._asin_elt _kind in
  map _func x


let asin_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._asin_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let acos x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._acos_elt _kind in
  map _func x


let acos_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._acos_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let atan x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._atan_elt _kind in
  map _func x


let atan_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._atan_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let asinh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._asinh_elt _kind in
  map _func x


let asinh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._asinh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let acosh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._acosh_elt _kind in
  map _func x


let acosh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._acosh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let atanh x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._atanh_elt _kind in
  map _func x


let atanh_ ?out x =
  let _kind = kind x in
  let _func = Owl_base_dense_common._atanh_elt _kind in
  let out = match out with Some o -> o | None -> x in
  map_ _func out


let sum_slices ?(axis=0) varr =
  let dims = shape varr in
  let rank = Array.length dims in
  (* reshape into 2d matrix *)
  let num_rows = Array.fold_left ( * ) 1 (Array.sub dims 0 (axis + 1)) in
  let num_cols = (numel varr) / num_rows in
  let varr_mat = reshape varr [|num_rows; num_cols|] in
  let result_vec = empty (kind varr) [|num_cols|] in
  let result_varr = reshape result_vec
      (Array.sub dims (axis + 1) (rank - axis - 1))
  in
  let row_sum = ref 0. in

  for j = 0 to num_cols - 1 do
    row_sum := 0.;
    for i = 0 to num_rows - 1 do
      row_sum := !row_sum +. (Genarray.get varr_mat [|i; j|])
    done;
    Genarray.set result_vec [|j|] !row_sum
  done;
  result_varr


(* -1. for negative numbers, 0 or (-0) for 0,
 1 for positive numbers, nan for nan*)
let signum x = map Scalar.signum x


let signum_ ?out x =
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.signum out


(* Apply 1 / (1 + exp (-x)) for each element x *)
let sigmoid x = map Scalar.sigmoid x


let sigmoid_ ?out x =
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.sigmoid out


let relu x = map Scalar.relu x


let relu_ ?out x =
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.relu out


let softsign x = map Scalar.softsign x


let softsign_ ?out x =
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.softsign out


let softplus x = map Scalar.softplus x


let softplus_ ?out x =
  let out = match out with Some o -> o | None -> x in
  map_ Scalar.softplus out


let _fold_left f a varr =
  let aref = ref a in
  let varr_linear = flatten varr |> array1_of_genarray in
  let length = numel varr in
  begin
    for i = 0 to length - 1 do
      aref := (f !aref (Array1.unsafe_get varr_linear i))
    done;
    !aref
  end


(* Min of all elements in the NDarray *)
let min' x =
  let _kind = kind x in
  let _max_val = Owl_base_dense_common._max_val_elt _kind in
  _fold_left (Owl_base_dense_common._min_elt _kind) _max_val x


(* Max of all elements in the NDarray *)
let max' x =
  let _kind = kind x in
  let _min_val = Owl_base_dense_common._min_val_elt _kind in
  _fold_left (Owl_base_dense_common._max_elt _kind) _min_val x


(* Sum of all elements *)
let sum' x =
  let _kind = kind x in
  _fold_left (Owl_base_dense_common._add_elt _kind) (Owl_const.zero _kind) x


(* Folding along a specified axis, aka reduction. The
   f: function of type 'a -> 'a -> 'a.
   m: number of slices.
   n: x's slice size.
   o: x's strides, also y's slice size.
   x: source; y: shape of destination. Note that o <= n.
 *)
let _fold_along ?out f m n o x ys nelem =
  let x = flatten x in
  let y = match out with
    | Some o -> o |> flatten
    | None   -> create (kind x) ys nelem |> flatten
  in
  let idx = ref 0 in
  let idy = ref 0 in
  let incy = ref 0 in
  for _i = 0 to (m - 1) do
    for j = 0 to (n - 1) do
      let addon = Genarray.get x [|!idx + j|] in
      let orig  = Genarray.get y [|!idy + !incy|] in
      Genarray.set y [|!idy + !incy|] (f orig addon);
      incy := if (!incy + 1 = o) then 0 else !incy + 1
    done;
    idx := !idx + n;
    idy := !idy + o;
  done;
  reshape y ys


let sum ?axis x =
  let _kind = kind x in
  let zero = Owl_const.zero _kind in
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      let _op = Owl_base_dense_common._add_elt _kind in
      _fold_along _op m n o x s zero
    )
  | None   -> create (kind x) (Array.make 1 1) (sum' x)


let sum_ ~out ~axis x =
  let _kind = kind x in
  let zero = Owl_const.zero _kind in
  Genarray.fill out zero;
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      let _op = Owl_base_dense_common._add_elt _kind in
      _fold_along _op ~out m n o x s zero
      |> ignore
    )
  | None   -> (
      let y = flatten out in
      set y [|0|] (sum' x)
    )


let sum_reduce ?axis x =
  let _kind = kind x in
  let _dims = num_dims x in
  let zero = Owl_const.zero _kind in
  match axis with
  | Some a -> (
      let x_shape = shape x in
      let dims' = Owl_utils.squeeze_continuous_dims x_shape a in
      if Array.length dims' = 1 then (
        create (kind x) (Array.make _dims 1) (sum' x)
      )
      else (
        let y = ref (reshape x dims') in
        let flag = ref (Array.mem 0 a) in
        for i = 0 to Array.length dims' - 1 do
          if !flag = true then (
            let m, n, o, s = Owl_utils.reduce_params i !y in
            y := _fold_along (Owl_base_dense_common._add_elt _kind) m n o !y s zero
          );
          flag := not !flag
        done;
        let y_shape = Array.copy x_shape in
        Array.iter (fun j -> y_shape.(j) <- 1) a;
        reshape !y y_shape
      )
    )
  | None   -> create (kind x) (Array.make _dims 1) (sum' x)


let min ?axis x =
  let _kind = kind x in
  let max_val = Owl_base_dense_common._max_val_elt _kind in
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      _fold_along (Owl_base_dense_common._min_elt _kind) m n o x s max_val
    )
  | None   -> min' x |> create _kind [|1|]


let min_ ~out ~axis x =
  let _kind = kind x in
  let max_val = Owl_base_dense_common._max_val_elt _kind in
  Genarray.fill out max_val;
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      let _op = Owl_base_dense_common._min_elt _kind in
      _fold_along ~out _op m n o x s max_val
      |> ignore
    )
  | None   -> (
      let y = flatten out in
      set y [|0|] (min' x)
    )


let max ?axis x =
  let _kind = kind x in
  let min_val = Owl_base_dense_common._min_val_elt _kind in
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      _fold_along (Owl_base_dense_common._max_elt _kind) m n o x s min_val
    )
  | None   -> max' x |> create _kind [|1|]


let max_ ~out ~axis x =
  let _kind = kind x in
  let min_val = Owl_base_dense_common._min_val_elt _kind in
  Genarray.fill out min_val;
  match axis with
  | Some a -> (
      let m, n, o, s = Owl_utils.reduce_params a x in
      _fold_along ~out (Owl_base_dense_common._max_elt _kind) m n o x s min_val
      |> ignore
    )
  | None   -> (
      let y = flatten out in
      set y [|0|] (max' x)
    )


let l1norm' varr =
  let l1norm_fun =
    (fun aggregate elem -> (aggregate +. (Scalar.abs (elem)))) in
  (_fold_left l1norm_fun 0. varr)


let l2norm_sqr' varr =
  let l2norm_sqr_fun =
    (fun aggregate elem -> (aggregate +. (elem *. elem))) in
  (_fold_left l2norm_sqr_fun 0. varr)


let l2norm' varr =
  let l2norm_sqr_val = l2norm_sqr' varr in
  (Scalar.sqrt l2norm_sqr_val)


let _broadcasted_op ?out varr_a varr_b op_fun =
  let (dims_a, dims_b, dims_c) =
    _get_broadcasted_dims (shape varr_a) (shape varr_b)
  in
  let _kind = kind varr_a in
  let varr_a = reshape varr_a dims_a in
  let varr_b = reshape varr_b dims_b in
  let varr_c = match out with
    | Some out -> out
    | None     -> empty _kind dims_c
  in
  let ind = Array.make (Array.length dims_c) 0 in
  let should_stop = ref false in
  begin
    while not !should_stop do
      let ind_a = _get_broadcasted_index ind dims_a in
      let ind_b = _get_broadcasted_index ind dims_b in
      Genarray.set varr_c ind
        (op_fun (Genarray.get varr_a ind_a) (Genarray.get varr_b ind_b));
      if not (_next_index ind dims_c) then
        should_stop := true
    done;
    varr_c
  end


let add x y =
  let _op = Owl_base_dense_common._add_elt (kind x) in
  _broadcasted_op x y _op


let add_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._add_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let sub x y =
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  _broadcasted_op x y _op


let sub_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let mul x y =
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  _broadcasted_op x y _op


let mul_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let div x y =
  let _op = Owl_base_dense_common._div_elt (kind x) in
  _broadcasted_op x y _op


let div_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._div_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let atan2 x y = _broadcasted_op x y (Scalar.atan2)


let atan2_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op x y (Scalar.atan2)
  |> ignore


let hypot x y = _broadcasted_op x y (Scalar.hypot)


let hypot_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op x y (Scalar.hypot)
  |> ignore


let pow x y =
  let _kind = kind x in
  let _op = Owl_base_dense_common._pow_elt _kind in
  _broadcasted_op x y _op


let pow_ ?out x y =
  let _kind = kind x in
  let _op = Owl_base_dense_common._pow_elt _kind in
  let out = match out with Some o -> o | None -> x in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let fmod x y = _broadcasted_op x y (Scalar.fmod)


let fmod_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op x y (Scalar.fmod)
  |> ignore


let min2 x y =
  let _op = Owl_base_dense_common._min_elt (kind x) in
  _broadcasted_op x y _op


let min2_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._min_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let max2 x y =
  let _op = Owl_base_dense_common._max_elt (kind x) in
  _broadcasted_op x y _op


let max2_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._max_elt (kind x) in
  let sx = shape x in
  let sy = shape y in
  let so = Owl_utils_infer_shape.broadcast1 sx sy in
  let st = shape out in
  let exn = Owl_exception.DIFFERENT_SHAPE (so, st) in
  Owl_exception.check (so = st) exn;
  _broadcasted_op ~out x y _op
  |> ignore


let add_scalar x a =
  let _op = Owl_base_dense_common._add_elt (kind x) in
  map (fun y -> _op y a) x


let add_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._add_elt (kind x) in
  map_ (fun y -> _op y a) out


let sub_scalar x a =
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  map (fun y -> _op y a) x


let sub_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  map_ (fun y -> _op y a) out


let mul_scalar x a =
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  map (fun y -> _op y a) x


let mul_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  map_ (fun y -> _op y a) out


let div_scalar x a =
  let _op = Owl_base_dense_common._div_elt (kind x) in
  map (fun y -> _op y a) x


let div_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._div_elt (kind x) in
  map_ (fun y -> _op y a) out


let pow_scalar x a =
  let _op = Owl_base_dense_common._pow_elt (kind x) in
  map (fun y -> _op y a) x


let pow_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._pow_elt (kind x) in
  map_ (fun y -> _op y a) out


let atan2_scalar x a =
  let _op = Scalar.atan2 in
  map (fun y -> _op y a) x


let atan2_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Scalar.atan2 in
  map_ (fun y -> _op y a) out


let fmod_scalar x a =
  let _op = Scalar.fmod in
  map (fun y -> _op y a) x


let fmod_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let _op = Scalar.fmod in
  map_ (fun y -> _op y a) out


(* TODO *)
let fma _x _y _z = failwith "Owl_base_dense_ndarray_generic:fma: not implemented"


let scalar_add a x =
  let _op = Owl_base_dense_common._add_elt (kind x) in
  map (fun y -> _op a y) x


let scalar_add_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._add_elt (kind x) in
  map_ (fun y -> _op a y) out


let scalar_sub a x =
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  map (fun y -> _op a y) x


let scalar_sub_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._sub_elt (kind x) in
  map_ (fun y -> _op a y) out


let scalar_mul a x =
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  map (fun y -> _op a y) x


let scalar_mul_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._mul_elt (kind x) in
  map_ (fun y -> _op a y) out


let scalar_div a x =
  let _op = Owl_base_dense_common._div_elt (kind x) in
  map (fun y -> _op a y) x


let scalar_div_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._div_elt (kind x) in
  map_ (fun y -> _op a y) out


let scalar_pow a x =
  let _op = Owl_base_dense_common._pow_elt (kind x) in
  map (fun y -> _op a y) x


let scalar_pow_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Owl_base_dense_common._pow_elt (kind x) in
  map_ (fun y -> _op a y) out


let scalar_atan2 a x =
  let _op = Scalar.atan2 in
  map (fun y -> _op a y) x


let scalar_atan2_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Scalar.atan2 in
  map_ (fun y -> _op a y) out


let scalar_fmod a x =
  let _op =Scalar.fmod in
  map (fun y -> _op a y) x


let scalar_fmod_ ?out a x =
  let out = match out with Some o -> o | None -> x in
  let _op = Scalar.fmod in
  map_ (fun y -> _op a y) out


let clip_by_value ?(amin=Stdlib.min_float) ?(amax=Stdlib.max_float) x =
  let _op = (fun y -> Stdlib.min amax (Stdlib.max amin y)) in
  map _op x


let clip_by_l2norm clip_norm x =
  let l2norm_val = l2norm' x in
  if l2norm_val > clip_norm then
    mul_scalar x (clip_norm /. l2norm_val)
  else x


let softmax ?(axis=(-1)) x =
  let x = copy x in
  let axis = Owl_utils.adjust_index axis (num_dims x) in
  sub_ ~out:x x (max ~axis x);
  exp_ ~out:x x;
  let a = sum ~axis x in
  div_ ~out:x x a;
  x


let softmax_ ?out ?(axis=(-1)) x =
  let out = match out with Some o -> o | None -> x in
  let axis = Owl_utils.adjust_index axis (num_dims x) in
  sub_ ~out x (max ~axis x);
  exp_ ~out x;
  let a = sum ~axis x in
  div_ ~out x a


(* Comparison functions *)

(** Return true if for all elements comp_fun (xa, xb) == true, false otherwise.
    Returns false as soon as it finds a counterexample. (NOT broadcasted) *)
let _compare_util_shortcircuit varr_a varr_b comp_fun =
  let n = numel varr_a in
  let m = numel varr_b in
  if n != m then
    false
  else
    let varr_a = flatten varr_a |> array1_of_genarray in
    let varr_b = flatten varr_b |> array1_of_genarray in
    let all_ok = ref true in
    let i = ref 0 in (
      while !all_ok && (!i < n) do
        let x = Array1.unsafe_get varr_a !i in
        let y = Array1.unsafe_get varr_b !i in
        if (not (comp_fun x y)) then all_ok := false;
        i := !i + 1
      done;
      !all_ok
    )


let approx_equal ?eps varr_a varr_b =
  let eps = match eps with
    | Some eps -> eps
    | None     -> Owl_utils.eps Float32
  in
  let approx_equal_fun = (fun x y -> (Scalar.abs (Scalar.sub x y)) < eps) in
  (_compare_util_shortcircuit varr_a varr_b approx_equal_fun)


let equal x y =
  (_compare_util_shortcircuit x y Stdlib.(=))


let not_equal x y =
  (_compare_util_shortcircuit x y Stdlib.(<>))


let less x y =
  (_compare_util_shortcircuit x y Stdlib.(<))


let greater x y =
  (_compare_util_shortcircuit x y Stdlib.(>))


let less_equal x y =
  (_compare_util_shortcircuit x y Stdlib.(<=))


let greater_equal x y =
  (_compare_util_shortcircuit x y Stdlib.(>=))


(** Return true if for all elements of a comp_fun (xa, bb) == true, false otherwise.
    Returns false as soon as it finds a counterexample. (NOT broadcasted) *)
let _compare_util_shortcircuit_scalar varr_a b comp_fun =
  let n = numel varr_a in
  let varr_a = flatten varr_a |> array1_of_genarray in
  let all_ok = ref true in
  let i = ref 0 in (
    while !all_ok && (!i < n) do
      let x = Array1.unsafe_get varr_a !i in
      if (not (comp_fun x b))
      then all_ok := false;
      i := !i + 1
    done;
    !all_ok
  )


let approx_equal_scalar ?eps varr_a b =
  let eps = match eps with
    | Some eps -> eps
    | None     -> Owl_utils.eps Float32
  in
  let approx_equal_scalar_fun = (fun x y -> (Scalar.abs (Scalar.sub x y)) < eps) in
  (_compare_util_shortcircuit_scalar varr_a b approx_equal_scalar_fun)


let equal_scalar x a =
  (_compare_util_shortcircuit_scalar x a Stdlib.(=))


let not_equal_scalar x a =
  (_compare_util_shortcircuit_scalar x a Stdlib.(<>))


let less_scalar x a =
  (_compare_util_shortcircuit_scalar x a Stdlib.(<))


let greater_scalar x a =
  (_compare_util_shortcircuit_scalar x a Stdlib.(>))


let less_equal_scalar varr_a b =
  (_compare_util_shortcircuit_scalar varr_a b Stdlib.(<=))


let greater_equal_scalar x a =
  (_compare_util_shortcircuit_scalar x a Stdlib.(>=))


(* Broadcasted operation, return an array with values of 1
   if (one_fun elem_from_a elem_from_b) == true, 0 otherwise *)
let _make_elt_compare_fun kind cmp_fun =
  let c0 = Owl_const.zero kind in
  let c1 = Owl_const.one kind in
  let _func a b = if cmp_fun a b then c1 else c0 in
  _func


let elt_equal x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(=) in
  _broadcasted_op x y _func


let elt_equal_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(=) in
  _broadcasted_op ~out x y _func


let approx_elt_equal ?eps x y =
  let eps = match eps with
    | Some eps -> eps
    | None     -> Owl_utils.eps Float32
  in
  let approx_equal_fun = (fun x y -> (Scalar.abs (Scalar.sub x y)) < eps) in
  let _func = _make_elt_compare_fun (kind x) approx_equal_fun in
  _broadcasted_op x y _func


let elt_not_equal x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<>) in
  _broadcasted_op x y _func


let elt_not_equal_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<>) in
  _broadcasted_op ~out x y _func


let elt_less x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<) in
  _broadcasted_op x y _func


let elt_less_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<) in
  _broadcasted_op ~out x y _func


let elt_greater x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(>) in
  _broadcasted_op x y _func


let elt_greater_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(>) in
  _broadcasted_op ~out x y _func


let elt_less_equal x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<=) in
  _broadcasted_op x y _func


let elt_less_equal_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(<=) in
  _broadcasted_op ~out x y _func


let elt_greater_equal x y =
  let _func = _make_elt_compare_fun (kind x) Stdlib.(>=) in
  _broadcasted_op x y _func


let elt_greater_equal_ ?out x y =
  let out = match out with Some o -> o | None -> x in
  let _func = _make_elt_compare_fun (kind x) Stdlib.(>=) in
  _broadcasted_op ~out x y _func


(* Util function, return an array with values of 1
    if (one_fun elem_from_a b) == true, 0 otherwise *)
let _make_elt_compare_scalar x cmp_fun =
  let _kind = kind x in
  let c0 = Owl_const.zero _kind in
  let c1 = Owl_const.one _kind in
  let _func a = if cmp_fun a then c1 else c0 in
  _func


let elt_equal_scalar x a =
  let cmp_fun = (fun y -> y = a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_equal_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y = a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map_ _func out


let approx_elt_equal_scalar ?eps x a =
  let eps = match eps with
    | Some eps -> eps
    | None     -> Owl_utils.eps Float32
  in
  let cmp_fun = (fun y -> (Scalar.abs (Scalar.sub y a)) < eps) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_not_equal_scalar x a =
  let cmp_fun = (fun y -> y <> a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_not_equal_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y <> a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map_ _func out


let elt_less_scalar x a =
  let cmp_fun = (fun y -> y < a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_less_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y < a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map_ _func out


let elt_greater_scalar x a =
  let cmp_fun = (fun y -> y > a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_greater_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y > a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map_ _func out


let elt_less_equal_scalar x a =
  let cmp_fun = (fun y -> y <= a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_less_equal_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y <= a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map_ _func out


let elt_greater_equal_scalar x a =
  let cmp_fun = (fun y -> y >= a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func x


let elt_greater_equal_scalar_ ?out x a =
  let out = match out with Some o -> o | None -> x in
  let cmp_fun = (fun y -> y >= a) in
  let _func = _make_elt_compare_scalar x cmp_fun in
  map _func out


let exists f x =
  let n = numel x in
  let x = flatten x |> array1_of_genarray in
  let found = ref false in
  let i = ref 0 in
  while (!i < n) && (not !found) do
    let a = Array1.unsafe_get x !i in
    if f a then found := true;
    i := !i + 1
  done;
  !found


let not_exists f varr = (not (exists f varr))


let for_all f varr =
  let not_f = (fun x -> not (f x)) in
  (not_exists not_f varr)


let is_zero varr =
  let k = kind varr in
  let c0 = Owl_const.zero k in
  let non_zero_fun = (fun x -> x <> c0) in
  (not_exists non_zero_fun varr)


let is_positive varr =
  let k = kind varr in
  let c0 = Owl_const.zero k in
  let non_positive_fun = (fun x -> x <= c0) in
  (not_exists non_positive_fun varr)


let is_negative varr =
  let k = kind varr in
  let c0 = Owl_const.zero k in
  let non_negative_fun = (fun x -> x >= c0) in
  (not_exists non_negative_fun varr)


let is_nonpositive varr =
  let k = kind varr in
  let c0 = Owl_const.zero k in
  let positive_fun = (fun x -> x > c0) in
  (not_exists positive_fun varr)


let is_nonnegative varr =
  let k = kind varr in
  let c0 = Owl_const.zero k in
  let negative_fun = (fun x -> x < c0) in
  (not_exists negative_fun varr)


let is_normal x =
  let _kind = kind x in
  let is_normal_fun = Owl_base_dense_common._is_normal_elt _kind in
  for_all is_normal_fun x


let not_nan x =
  let _kind = kind x in
  let is_nan_fun = Owl_base_dense_common._is_nan_elt _kind in
  not_exists is_nan_fun x


let not_inf x =
  let _kind = kind x in
  let is_inf_fun = Owl_base_dense_common._is_inf_elt _kind in
  not_exists is_inf_fun x


(* Neural network related functions *)

(*TODO: optimise *)
(* conv2d: 4d input and 4d kernel, refer to tensorlfow doc
   input : [batch; input_column; input_row; input_channel]
   kernel: [kernel_column; kernel_row; input_channel; output_channel]
   stride: [column_stride; row_stride]
   output: [batch; output_column; output_row; output_channel]
*)
let conv2d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 4) in
  let p1 = (num_dims kernel = 4) in
  let p2 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 4)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s3 = Printf.sprintf "conv2d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let out_channel = kernel_shp.(3) in
  let p3 = (in_channel = kernel_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 4th dimension of input shape should be equal to the 3rd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv2d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let (output_cols, output_rows) =
    Owl_utils_infer_shape.calc_conv2d_output_shape padding input_cols input_rows
      kernel_cols kernel_rows row_stride col_stride
  in
  let _kind = kind input in
  let output = empty _kind [|batches; output_cols; output_rows; out_channel|] in
  let (pad_top, pad_left, _, _) = Owl_utils_infer_shape.calc_conv2d_padding
      input_cols input_rows kernel_cols kernel_rows output_cols output_rows
      row_stride col_stride
  in
  let sum = ref 0. in
  begin
    for b = 0 to batches - 1 do
      for i = 0 to output_cols - 1 do
        for j = 0 to output_rows - 1 do
          for k = 0 to out_channel - 1 do
            sum := 0.;

            for di = 0 to kernel_cols - 1 do
              for dj = 0 to kernel_rows - 1 do
                for q = 0 to in_channel - 1 do
                  let in_col = i * col_stride + di - pad_left in
                  let in_row = j * row_stride + dj - pad_top in
                  let in_val = (
                    if ((0 <= in_col) && (in_col < input_cols) &&
                        (0 <= in_row) && (in_row < input_rows))
                    then (get input [|b; in_col; in_row; q|])
                    else 0.
                  ) in
                  sum := !sum +. in_val *. (get kernel [|di; dj; q; k|])
                done; (*q*)
              done; (*dj*)
            done; (*di*)

            (set output [|b; i; j; k|] !sum)
          done; (*k*)
        done; (*j*)
      done; (*i*)
    done; (*b*)
    output
  end


(* conv1d: 3d input and 3d kernel, refer to tensorlfow doc
   input : [batch; input_column; input_channel]
   kernel: [kernel_column; input_channel; output_channel]
   stride: [column_stride]
   output: [batch; output_column; output_channel]
*)
let conv1d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "conv1d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; 1; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p3 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3rd dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv1d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let kernel = reshape kernel [|1; kernel_cols; in_channel; out_channel|] in

  let col_stride = stride.(0) in
  let stride = [|1; col_stride|] in

  let output = conv2d ~padding input kernel stride in
  let output_shp = shape output in
  let output_cols = output_shp.(2) in
  let output = reshape output [|batches; output_cols; out_channel|] in
  output

  (* TODO: optimise *)
  (* conv3d: 5d input and 5d kernel, refer to tensorflow doc
    input : [batch; input_column; input_row; input_depth; input_channel]
    kernel: [kernel_column; kernel_row; kernel_depth; input_channel; output_channel]
    stride: [column_stride; row_stride; depth_stride]
    output: [batch; output_column; output_row; output_dpts; output_channel]
   *)
  let conv3d ?(padding=SAME) input kernel stride =
    let p0 = (num_dims input = 5) in
    let p1 = (num_dims kernel = 5) in
    let p2 = (Array.length stride = 3) in

    let error () =
      let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
      let s1 = Printf.sprintf "kernel dimension = %i (should be 5)" (num_dims kernel) in
      let s2 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
      let s3 = Printf.sprintf "conv3d: %s; %s; %s." s0 s1 s2 in
      Owl_exception.INVALID_ARGUMENT s3
    in
    Owl_exception.verify (p0 && p1 && p2) error;

    let input_shp = shape input in
    let batches = input_shp.(0) in
    let input_cols = input_shp.(1) in
    let input_rows = input_shp.(2) in
    let input_dpts = input_shp.(3) in
    let in_channel = input_shp.(4) in

    let kernel_shp = shape kernel in
    let kernel_cols = kernel_shp.(0) in
    let kernel_rows = kernel_shp.(1) in
    let kernel_dpts = kernel_shp.(2) in
    let out_channel = kernel_shp.(4) in
    let p3 = (in_channel = kernel_shp.(3)) in

    let error () =
      let s0 = Owl_utils_array.to_string string_of_int input_shp in
      let s1 = Printf.sprintf "input shape is [%s]" s0 in
      let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
      let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
      let s4 = Printf.sprintf "the 5th dimension of input shape should be equal to the 4th dimension of kernel shape" in
      let s5 = Printf.sprintf "conv3d: %s, %s, %s." s1 s3 s4 in
      Owl_exception.INVALID_ARGUMENT s5
    in
    Owl_exception.verify p3 error;

    let col_stride = stride.(0) in
    let row_stride = stride.(1) in
    let dpt_stride = stride.(2) in

    let output_cols, output_rows, output_dpts =
      Owl_utils_infer_shape.calc_conv3d_output_shape padding
        input_cols input_rows input_dpts
        kernel_cols kernel_rows kernel_dpts
        row_stride col_stride dpt_stride
    in
    let _kind = kind input in
    let output =
      empty _kind [|batches; output_cols; output_rows; output_dpts; out_channel|] in
    let (pad_top, pad_left, pad_shallow, _, _, _) =
      Owl_utils_infer_shape.calc_conv3d_padding
        input_cols input_rows input_dpts
        kernel_cols kernel_rows kernel_dpts
        output_cols output_rows output_dpts
        row_stride col_stride dpt_stride
    in
    let sum = ref 0. in
    begin
      for b = 0 to batches - 1 do
        for i = 0 to output_cols - 1 do
          for j = 0 to output_rows - 1 do
            for dpt = 0 to output_dpts - 1 do
              for k = 0 to out_channel - 1 do
                sum := 0.;

                for di = 0 to kernel_cols - 1 do
                  for dj = 0 to kernel_rows - 1 do
                    for d_dpt = 0 to kernel_dpts -1 do
                      for q = 0 to in_channel - 1 do
                        let in_col = i * col_stride + di - pad_left in
                        let in_row = j * row_stride + dj - pad_top in
                        let in_dpt = dpt * dpt_stride + d_dpt - pad_shallow in
                        let in_val = (
                          if ((0 <= in_col) && (in_col < input_cols) &&
                              (0 <= in_row) && (in_row < input_rows) &&
                              (0 <= in_dpt) && (in_dpt < input_dpts))
                          then (get input [|b; in_col; in_row; in_dpt; q|])
                          else 0.
                        ) in
                        sum := !sum +. in_val *. (get kernel [|di; dj; d_dpt; q; k|])
                      done; (*q*)
                    done; (*d_dpt*)
                  done; (*dj*)
                done; (*di*)

                (set output [|b; i; j; dpt; k|] !sum)
              done; (*k*)
            done; (*dpt*)
          done; (*j*)
        done; (*i*)
      done; (*b*)
      output
    end


(* General function for avg_pool2d and max_pool2d *)
let _pool2d ?(padding=SAME) input kernel stride
      init_pool_fun add_val_pool_fun end_pool_fun =
  let p0 = (num_dims input = 4) in
  let p1 = (Array.length kernel = 2) in
  let p2 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 2)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s3 = Printf.sprintf "_pool2d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_cols = kernel.(0) in
  let kernel_rows = kernel.(1) in

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let (output_cols, output_rows) =
    Owl_utils_infer_shape.calc_conv2d_output_shape padding
      input_cols input_rows
      kernel_cols kernel_rows
      row_stride col_stride
  in
  let _kind = kind input in
  let output = empty _kind [|batches; output_cols; output_rows; in_channel|] in
  let (pad_top, pad_left, _, _) = Owl_utils_infer_shape.calc_conv2d_padding
      input_cols input_rows kernel_cols kernel_rows output_cols output_rows
      row_stride col_stride
  in
  begin
    for b = 0 to batches - 1 do
      for i = 0 to output_cols - 1 do
        for j = 0 to output_rows - 1 do
          for k = 0 to in_channel - 1 do
            init_pool_fun ();

            for di = 0 to kernel_cols - 1 do
              for dj = 0 to kernel_rows - 1 do
                let in_col = i * col_stride + di - pad_left in
                let in_row = j * row_stride + dj - pad_top in
                if ((0 <= in_col) && (in_col < input_cols) &&
                    (0 <= in_row) && (in_row < input_rows))
                then add_val_pool_fun (get input [|b; in_col; in_row; k|])
              done; (*dj*)
            done; (*di*)

            (set output [|b; i; j; k|] (end_pool_fun ()))
          done; (*k*)
        done; (*j*)
      done; (*i*)
    done; (*b*)
    output
  end


let _pool3d ?(padding=SAME) input kernel stride
    init_pool_fun add_val_pool_fun end_pool_fun =
  let p0 = (num_dims input = 5) in
  let p1 = (Array.length kernel = 3) in
  let p2 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s3 = Printf.sprintf "_pool3d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_cols = kernel.(0) in
  let kernel_rows = kernel.(1) in
  let kernel_dpts = kernel.(2) in

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let output_cols, output_rows, output_dpts =
    Owl_utils_infer_shape.calc_conv3d_output_shape padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      row_stride col_stride dpt_stride
  in
  let _kind = kind input in
  let output = empty _kind [|batches; output_cols; output_rows; output_dpts; in_channel|] in
  let (pad_top, pad_left, pad_shallow, _, _, _) =
    Owl_utils_infer_shape.calc_conv3d_padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      output_cols output_rows output_dpts
      row_stride col_stride dpt_stride
  in
  begin
    for b = 0 to batches - 1 do
      for i = 0 to output_cols - 1 do
        for j = 0 to output_rows - 1 do
          for dpt = 0 to output_dpts - 1 do
            for k = 0 to in_channel - 1 do
              init_pool_fun ();

              for di = 0 to kernel_cols - 1 do
                for dj = 0 to kernel_rows - 1 do
                  for d_dpt = 0 to kernel_dpts - 1 do
                    let in_col = i * col_stride + di - pad_left in
                    let in_row = j * row_stride + dj - pad_top in
                    let in_dpt = dpt * dpt_stride + d_dpt - pad_shallow in
                    if ((0 <= in_col) && (in_col < input_cols) &&
                        (0 <= in_row) && (in_row < input_rows)  &&
                        (0 <= in_dpt) && (in_dpt < input_dpts))
                    then add_val_pool_fun
                        (get input [|b; in_col; in_row; in_dpt; k|])
                  done; (*d_dpt*)
                done; (*dj*)
              done; (*di*)

              (set output [|b; i; j; dpt; k|] (end_pool_fun ()))
            done; (*k*)
          done; (*dpt*)
        done; (*j*)
      done; (*i*)
    done; (*b*)
    output
  end


(* max_pool2d: 4d input and 2d kernel, refer to tensorlfow doc
   input : [batch; input_column; input_row; input_channel]
   kernel: [kernel_column; kernel_row]
   stride: [column_stride; row_stride]
   output: [batch; output_column; output_row; input_channel]
*)
let max_pool2d ?(padding=SAME) input kernel stride =
  let max_pool = ref 0. in
  let init_pool_fun = (fun () -> max_pool := Stdlib.min_float) in
  let add_val_pool_fun =
    (fun v -> max_pool := Stdlib.max !max_pool v)
  in
  let end_pool_fun = (fun () -> !max_pool) in
  (_pool2d ~padding:padding input kernel stride
     init_pool_fun add_val_pool_fun end_pool_fun)

(* max_pool1d: 3d input and 1d kernel, refer to tensorlfow doc
   input : [batch; input_column; input_channel]
   kernel: [kernel_column]
   stride: [column_stride]
   output: [batch; output_column; input_channel]
*)
let max_pool1d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 3) in
  let p1 = (Array.length kernel = 1) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 1)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "max_pool1d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; 1; input_cols; in_channel|] in

  let kernel_cols = kernel.(0) in
  let kernel = [|1; kernel_cols|] in

  let col_stride = stride.(0) in
  let stride = [|1; col_stride|] in

  let output = max_pool2d ~padding input kernel stride in
  let output_shp = shape output in
  let output_cols = output_shp.(2) in
  let output = reshape output [|batches; output_cols; in_channel|] in
  output


(* max_pool3d: 5d input and 3d kernel, refer to tensorflow doc
input : [batch; input_column; input_row; input_depth; input_channel]
kernel: [kernel_column; kernel_row; kernel_depth]
stride: [column_stride; row_stride; depth_stride]
output: [batch; output_column; output_row; output_dpts; input_channel]
*)
let max_pool3d ?(padding=SAME) input kernel stride =
  let max_pool = ref 0. in
  let init_pool_fun = (fun () -> max_pool := Stdlib.min_float) in
  let add_val_pool_fun =
    (fun v -> max_pool := Stdlib.max !max_pool v)
  in
  let end_pool_fun = (fun () -> !max_pool) in
  (_pool3d ~padding:padding input kernel stride
     init_pool_fun add_val_pool_fun end_pool_fun)


(* similar to max_pool2d *)
let avg_pool2d ?(padding=SAME) input kernel stride =
  let sum_pool = ref 0. in
  let cnt = ref 0. in
  let init_pool_fun = (fun () -> (sum_pool := 0.; cnt := 0.)) in
  let add_val_pool_fun =
    (fun v -> sum_pool := !sum_pool +. v; cnt := !cnt +. 1.)
  in
  let end_pool_fun = (fun () -> (!sum_pool /. !cnt)) in
  (_pool2d ~padding:padding input kernel stride
     init_pool_fun add_val_pool_fun end_pool_fun)


(* similar to max_pool1d *)
let avg_pool1d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 3) in
  let p1 = (Array.length kernel = 1) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 1)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "avg_pool1d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; 1; input_cols; in_channel|] in

  let kernel_cols = kernel.(0) in
  let kernel = [|1; kernel_cols|] in

  let col_stride = stride.(0) in
  let stride = [|1; col_stride|] in

  let output = avg_pool2d ~padding input kernel stride in
  let output_shp = shape output in
  let output_cols = output_shp.(2) in
  let output = reshape output [|batches; output_cols; in_channel|] in
  output


(* simiar to max_pool3d *)
let avg_pool3d ?(padding=SAME) input kernel stride =
  let sum_pool = ref 0. in
  let cnt = ref 0. in
  let init_pool_fun = (fun () -> (sum_pool := 0.; cnt := 0.)) in
  let add_val_pool_fun =
    (fun v -> sum_pool := !sum_pool +. v; cnt := !cnt +. 1.)
  in
  let end_pool_fun = (fun () -> (!sum_pool /. !cnt)) in
  (_pool3d ~padding:padding input kernel stride
     init_pool_fun add_val_pool_fun end_pool_fun)


(*TODO: optimise *)
(* gradient of conv2d w.r.t the input *)
let conv2d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 4) in
  let p1 = (num_dims kernel = 4) in
  let p2 = (num_dims output' = 4) in
  let p3 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 4)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 4)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s4 = Printf.sprintf "conv2d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let out_channel = kernel_shp.(3) in
  let p4 = (in_channel = kernel_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 4th dimension of input shape should be equal to the 3rd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv2d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 4th dimension of kernel shape should be equal to the 4th dimension of output' shape" in
    let s8 = Printf.sprintf "conv2d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let input' = empty (kind input) (shape input) in
  let (pad_top, pad_left, _, _) = Owl_utils_infer_shape.calc_conv2d_padding
      input_cols input_rows kernel_cols kernel_rows output_cols output_rows
      row_stride col_stride
  in
  begin
    for b = 0 to batches - 1 do
      for in_i = 0 to input_cols - 1 do
        for in_j = 0 to input_rows - 1 do
          for q = 0 to in_channel - 1 do
            let sum = ref 0. in

            for di = 0 to kernel_cols - 1 do
              for dj = 0 to kernel_rows - 1 do
                if ( ((Stdlib.(mod) (in_i + pad_left - di) col_stride) = 0) &&
                     ((Stdlib.(mod) (in_j + pad_top - dj) row_stride) = 0) )
                then
                  begin
                    let out_col = (in_i + pad_left - di) / col_stride in
                    let out_row = (in_j + pad_top - dj) / row_stride in
                    if ((0 <= out_col) && (out_col < output_cols) &&
                        (0 <= out_row) && (out_row < output_rows))
                    then
                      for k = 0 to out_channel - 1 do
                        let out_grad = get output' [|b; out_col; out_row; k|] in
                        let kernel_val = get kernel [|di; dj; q; k|] in
                        sum := !sum +. out_grad *. kernel_val
                      done; (*k*)
                  end
              done; (*dj*)
            done; (*di*)

            (set input' [|b; in_i; in_j; q|] !sum)
          done; (*q*)
        done; (*in_j*)
      done; (*in_i*)
    done; (*b*)
    input'
  end


(* gradient of conv2d w.r.t the kernel *)
let conv2d_backward_kernel input kernel stride output' =
  let p0 = (num_dims input = 4) in
  let p1 = (num_dims kernel = 4) in
  let p2 = (num_dims output' = 4) in
  let p3 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 4)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 4)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s4 = Printf.sprintf "conv2d_backward_kernel: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let out_channel = kernel_shp.(3) in
  let p4 = (in_channel = kernel_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 4th dimension of input shape should be equal to the 3rd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv2d_backward_kernel: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 4th dimension of kernel shape should be equal to the 4th dimension of output' shape" in
    let s8 = Printf.sprintf "conv2d_backward_kernel: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let kernel' = empty (kind kernel) (shape kernel) in

  let (pad_top, pad_left, _, _) = Owl_utils_infer_shape.calc_conv2d_padding
      input_cols input_rows kernel_cols kernel_rows output_cols output_rows
      row_stride col_stride
  in
  begin
    for di = 0 to kernel_cols - 1 do
      for dj = 0 to kernel_rows - 1 do
        for q = 0 to in_channel - 1 do
          for k = 0 to out_channel - 1 do
            let sum = ref 0. in

            for b = 0 to batches - 1 do
              for i = 0 to output_cols - 1 do
                for j = 0 to output_rows - 1 do
                  let in_col = i * col_stride + di - pad_left in
                  let in_row = j * row_stride + dj - pad_top in
                  if ((0 <= in_col) && (in_col < input_cols) &&
                      (0 <= in_row) && (in_row < input_rows))
                  then
                    let out_grad = get output' [|b; i; j; k|] in
                    let input_val = get input [|b; in_col; in_row; q|] in
                    sum := !sum +. out_grad *. input_val
                done; (*j*)
              done; (*i*)
            done; (*b*)

            set kernel' [|di; dj; q; k|] !sum
          done; (*k*)
        done; (*q*)
      done; (*dj*)
    done; (*di*)
    kernel'
  end


let transpose ?axis varr =
  let dims = shape varr in
  let rank = Array.length dims in
  let axis_perm = match axis with
    | Some perm -> perm
    | None -> Array.init rank (fun i -> rank - i - 1)
  in
  let new_dims = _apply_perm dims axis_perm in
  let new_varr = empty (kind varr) new_dims in
  let ind = Array.make rank 0 in
  let should_stop = ref false in
  begin
    while not !should_stop do
      Genarray.set new_varr
        (_apply_perm ind axis_perm) (Genarray.get varr ind);
      if not (_next_index ind dims) then
        should_stop := true
    done;
    new_varr
  end


(* transpose_conv2d: 4d input and 4d kernel, refer to tensorlfow doc
  input : [batch; input_column; input_row; input_channel]
  kernel: [kernel_column; kernel_row; input_channel; output_channel]
  stride: [column_stride; row_stride]
  output: [batch; output_column; output_row; output_channel]
 *)
let transpose_conv2d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 4) in
  let p1 = (num_dims kernel = 4) in
  let p2 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 4)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s3 = Printf.sprintf "transpose_conv2d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let out_channel = kernel_shp.(3) in
  let p3 = (in_channel = kernel_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 4th dimension of input shape should be equal to the 3rd dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv2d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let output_cols, output_rows = Owl_utils_infer_shape.calc_transpose_conv2d_output_shape
    padding input_cols input_rows kernel_cols kernel_rows
    row_stride col_stride
  in
  let output' = empty (kind input) [|batches; output_cols; output_rows;
    out_channel|]
  in
  let kernel = transpose ~axis:[|0;1;3;2|] kernel in
  conv2d_backward_input output' kernel stride input


(* gradient of transpose_conv2d w.r.t the input *)
let transpose_conv2d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 4) in
  let p1 = (num_dims kernel = 4) in
  let p2 = (num_dims output' = 4) in
  let p3 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 4)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 4)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s4 = Printf.sprintf "transpose_conv2d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let out_channel = kernel_shp.(3) in
  let p4 = (in_channel = kernel_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 4th dimension of input shape should be equal to the 3rd dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv2d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 4th dimension of kernel shape should be equal to the 4th dimension of output' shape" in
    let s8 = Printf.sprintf "transpose_conv2d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let padding = SAME in
  let output_cols_same, output_rows_same =
    Owl_utils_infer_shape.calc_transpose_conv2d_output_shape
      padding input_cols input_rows kernel_cols kernel_rows
      row_stride col_stride
  in

  let p = if ((output_cols_same = output_cols)
    && (output_rows_same = output_rows) ) then SAME else VALID
  in
  let kernel = transpose ~axis:[|0;1;3;2|] kernel in
  conv2d ~padding:p output' kernel stride


(* gradient of transpose_conv2d w.r.t the kernel *)
let transpose_conv2d_backward_kernel input kernel stride output' =
  conv2d_backward_kernel output' kernel stride input


(* transpose_conv1d: 3d input and 3d kernel, refer to tensorlfow doc
   input : [batch; input_column; input_channel]
   kernel: [kernel_column; input_channel; output_channel]
   stride: [column_stride]
   output: [batch; output_column; output_channel]
 *)
let transpose_conv1d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "transpose_conv1d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; 1; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p3 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3rd dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv1d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let kernel = reshape kernel [|1; kernel_cols; in_channel; out_channel|] in

  let col_stride = stride.(0) in
  let stride = [|1; col_stride|] in

  let output = transpose_conv2d ~padding input kernel stride in
  let output_shp = shape output in
  let output_cols = output_shp.(2) in
  let output = reshape output [|batches; output_cols; out_channel|] in
  output


(* gradient of conv1d w.r.t the input *)
let conv1d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "conv1d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv1d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "conv1d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;
  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let input' = conv2d_backward_input input kernel stride output' in
  reshape input' input_shp


(* gradient of conv1d w.r.t the kernel *)
let conv1d_backward_kernel input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "conv1d_backward_kernel: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "conv1d_backward_kernel: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "conv1d_backward_kernel: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let kernel' = conv2d_backward_kernel input kernel stride output' in
  reshape kernel' kernel_shp


(* gradient of transpose_conv1d w.r.t the input *)
let transpose_conv1d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "transpose_conv1d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv1d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "transpose_conv1d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let input' = transpose_conv2d_backward_input input kernel stride output' in
  reshape input' input_shp


(* gradient of conv1d w.r.t the kernel *)
let transpose_conv1d_backward_kernel input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "transpose_conv1d_backward_kernel: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv1d_backward_kernel: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "transpose_conv1d_backward_kernel: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let kernel' = transpose_conv2d_backward_kernel input kernel stride output' in
  reshape kernel' kernel_shp


(*TODO: optimise *)
(* gradient of conv3d w.r.t the input *)
let conv3d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 5) in
  let p1 = (num_dims kernel = 5) in
  let p2 = (num_dims output' = 5) in
  let p3 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 5)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 5)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s4 = Printf.sprintf "conv3d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let kernel_dpts = kernel_shp.(2) in
  let out_channel = kernel_shp.(4) in
  let p4 = (in_channel = kernel_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 5th dimension of input shape should be equal to the 4th dimension of kernel shape" in
    let s5 = Printf.sprintf "conv3d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let output_dpts =  output_shp.(3) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(4)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 5th dimension of kernel shape should be equal to the 5th dimension of output' shape" in
    let s8 = Printf.sprintf "conv3d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let input' = empty (kind input) (shape input) in
  let (pad_top, pad_left, pad_shallow, _, _, _) =
    Owl_utils_infer_shape.calc_conv3d_padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      output_cols output_rows output_dpts
      row_stride col_stride dpt_stride
  in
  begin
    for b = 0 to batches - 1 do
      for in_i = 0 to input_cols - 1 do
        for in_j = 0 to input_rows - 1 do
          for in_dpt = 0 to input_dpts - 1 do
            for q = 0 to in_channel - 1 do
              let sum = ref 0. in

              for di = 0 to kernel_cols - 1 do
                for dj = 0 to kernel_rows - 1 do
                  for d_dpt = 0 to kernel_dpts - 1 do
                    if ( ((Stdlib.(mod) (in_i + pad_left - di) col_stride) = 0) &&
                         ((Stdlib.(mod) (in_j + pad_top - dj) row_stride) = 0) &&
                         ((Stdlib.(mod) (in_dpt + pad_shallow - d_dpt) dpt_stride) = 0))
                    then
                      begin
                        let out_col = (in_i + pad_left - di) / col_stride in
                        let out_row = (in_j + pad_top - dj) / row_stride in
                        let out_dpt = (in_dpt + pad_shallow - d_dpt) / dpt_stride in
                        if ((0 <= out_col) && (out_col < output_cols) &&
                            (0 <= out_row) && (out_row < output_rows) &&
                            (0 <= out_dpt) && (out_dpt < output_dpts))
                        then
                          for k = 0 to out_channel - 1 do
                            let out_grad = get output' [|b; out_col; out_row; out_dpt; k|] in
                            let kernel_val = get kernel [|di; dj; d_dpt; q; k|] in
                            sum := !sum +. out_grad *. kernel_val
                          done; (*k*)
                      end
                done; (*d_dpt*)
                done; (*dj*)
              done; (*di*)

              (set input' [|b; in_i; in_j; in_dpt; q|] !sum)
            done; (*q*)
          done; (*in_dpt*)
        done; (*in_j*)
      done; (*in_i*)
    done; (*b*)
    input'
  end


  (* gradient of conv3d w.r.t the kernel *)
let conv3d_backward_kernel input kernel stride output' =
  let p0 = (num_dims input = 5) in
  let p1 = (num_dims kernel = 5) in
  let p2 = (num_dims output' = 5) in
  let p3 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 5)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 5)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s4 = Printf.sprintf "conv3d_backward_kernel: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let kernel_dpts = kernel_shp.(2) in
  let out_channel = kernel_shp.(4) in
  let p4 = (in_channel = kernel_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 5th dimension of input shape should be equal to the 4th dimension of kernel shape" in
    let s5 = Printf.sprintf "conv2d_backward_kernel: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let output_dpts =  output_shp.(3) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(4)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 5th dimension of kernel shape should be equal to the 5th dimension of output' shape" in
    let s8 = Printf.sprintf "conv2d_backward_kernel: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let kernel' = empty (kind kernel) (shape kernel) in

  let (pad_top, pad_left, pad_shallow, _, _, _) =
    Owl_utils_infer_shape.calc_conv3d_padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      output_cols output_rows output_dpts
      row_stride col_stride dpt_stride
  in
  begin
    for di = 0 to kernel_cols - 1 do
      for dj = 0 to kernel_rows - 1 do
        for d_dpt = 0 to kernel_dpts - 1 do
          for q = 0 to in_channel - 1 do
            for k = 0 to out_channel - 1 do
              let sum = ref 0. in

              for b = 0 to batches - 1 do
                for i = 0 to output_cols - 1 do
                  for j = 0 to output_rows - 1 do
                    for dpt = 0 to output_dpts - 1 do
                      let in_col = i * col_stride + di - pad_left in
                      let in_row = j * row_stride + dj - pad_top in
                      let in_dpt = dpt * dpt_stride + d_dpt - pad_shallow in
                      if ((0 <= in_col) && (in_col < input_cols) &&
                          (0 <= in_row) && (in_row < input_rows) &&
                          (0 <= in_dpt) && (in_dpt < input_dpts))
                      then
                        let out_grad = get output' [|b; i; j; dpt; k|] in
                        let input_val = get input [|b; in_col; in_row; in_dpt; q|] in
                        sum := !sum +. out_grad *. input_val
                    done; (*dpt*)
                  done; (*j*)
                done; (*i*)
              done; (*b*)

              set kernel' [|di; dj; d_dpt; q; k|] !sum
            done; (*k*)
          done; (*q*)
        done; (*d_dpt*)
      done; (*dj*)
    done; (*di*)
    kernel'
  end


(* transpose_conv3d: 5d input and 5d kernel, refer to tensorflow doc
  input : [batch; input_column; input_row; input_depth; input_channel]
  kernel: [kernel_column; kernel_row; kernel_depth; input_channel; output_channel]
  stride: [column_stride; row_stride; depth_stride]
  output: [batch; output_column; output_row; output_dpts; output_channel]
 *)
let transpose_conv3d ?(padding=SAME) input kernel stride =
  let p0 = (num_dims input = 5) in
  let p1 = (num_dims kernel = 5) in
  let p2 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 5)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s3 = Printf.sprintf "transpose_conv3d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let kernel_dpts = kernel_shp.(2) in
  let out_channel = kernel_shp.(4) in
  let p3 = (in_channel = kernel_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 5th dimension of input shape should be equal to the 4th dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv3d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let output_cols, output_rows, output_dpts =
    Owl_utils_infer_shape.calc_conv3d_output_shape padding input_cols input_rows input_dpts kernel_cols kernel_rows kernel_dpts row_stride col_stride dpt_stride
  in
  let output = empty (kind input) [|batches; output_cols; output_rows; output_dpts; out_channel|] in

  let kernel = transpose ~axis:[|0;1;2;4;3|] kernel in
  conv3d_backward_input output kernel stride input


(* gradient of transpose_conv3d w.r.t the input *)
let transpose_conv3d_backward_input input kernel stride output' =
  let p0 = (num_dims input = 5) in
  let p1 = (num_dims kernel = 5) in
  let p2 = (num_dims output' = 5) in
  let p3 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 5)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 5)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s4 = Printf.sprintf "transpose_conv3d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let kernel_rows = kernel_shp.(1) in
  let kernel_dpts = kernel_shp.(2) in
  let out_channel = kernel_shp.(4) in
  let p4 = (in_channel = kernel_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 5th dimension of input shape should be equal to the 4th dimension of kernel shape" in
    let s5 = Printf.sprintf "transpose_conv3d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let output_dpts =  output_shp.(3) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (out_channel = output_shp.(4)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 5th dimension of kernel shape should be equal to the 5th dimension of output' shape" in
    let s8 = Printf.sprintf "transpose_conv3d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let padding = SAME in
  let output_cols_same, output_rows_same, output_dpts_same =
    Owl_utils_infer_shape.calc_conv3d_output_shape padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      row_stride col_stride dpt_stride
  in
  let p = if ((output_cols_same = output_cols)
    && (output_rows_same = output_rows)
    && (output_dpts_same = output_dpts)) then SAME else VALID
  in
  let kernel = transpose ~axis:[|0;1;2;4;3|] kernel in
  conv3d ~padding:p output' kernel stride


(* gradient of transpose_conv3d w.r.t the kernel *)
let transpose_conv3d_backward_kernel input kernel stride output' =
  conv3d_backward_kernel output' kernel stride input


(* TODO: definitely optimise *)
(* General function for avg_pool2d and max_pool2d *)
let _pool2d_backward _padding input kernel stride output'
    init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun =
  let p0 = (num_dims input = 4) in
  let p1 = (Array.length kernel = 2) in
  let p2 = (Array.length stride = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 2)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 2)" (Array.length stride) in
    let s3 = Printf.sprintf "_pool2d_backward: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let kernel_cols = kernel.(0) in
  let kernel_rows = kernel.(1) in

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (in_channel = output_shp.(3)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Printf.sprintf "input shape is [%s]" s0 in
    let s3 = Printf.sprintf "output' shape is [%s]" s1 in
    let s4 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s5 = Printf.sprintf "the 4th dimension of input shape should be equal to the 4th dimension of output' shape" in
    let s6 = Printf.sprintf "_pool2d_backward: %s; %s; %s; %s." s2 s3 s4 s5 in
    Owl_exception.INVALID_ARGUMENT s6
  in
  Owl_exception.verify (p5 && p6) error;

  let (pad_top, pad_left, _, _) = Owl_utils_infer_shape.calc_conv2d_padding
      input_cols input_rows kernel_cols kernel_rows output_cols output_rows
      row_stride col_stride
  in
  let input' = zeros (kind input) (shape input) in
  begin
    for b = 0 to batches - 1 do
      for i = 0 to output_cols - 1 do
        for j = 0 to output_rows - 1 do
          for k = 0 to in_channel - 1 do
            init_pool_fun ();

            for di = 0 to kernel_cols - 1 do
              for dj = 0 to kernel_rows - 1 do
                let in_col = i * col_stride + di - pad_left in
                let in_row = j * row_stride + dj - pad_top in
                if ((0 <= in_col) && (in_col < input_cols) &&
                    (0 <= in_row) && (in_row < input_rows))
                then add_val_pool_fun (get input [|b; in_col; in_row; k|])
              done; (*dj*)
            done; (*di*)

            let output_val = end_pool_fun () in
            let output_grad = get output' [|b; i; j; k|] in
            for di = 0 to kernel_cols - 1 do
              for dj = 0 to kernel_rows - 1 do
                let in_col = i * col_stride + di - pad_left in
                let in_row = j * row_stride + dj - pad_top in
                if ((0 <= in_col) && (in_col < input_cols) &&
                    (0 <= in_row) && (in_row < input_rows))
                then
                  let input_val = (get input [|b; in_col; in_row; k|]) in
                  let input_grad = (get input' [|b; in_col; in_row; k|]) in
                  set input' [|b; in_col; in_row; k|] (compute_grad_fun input_val input_grad output_val output_grad)
              done; (*dj*)
            done; (*di*)

          done; (*k*)
        done; (*j*)
      done; (*i*)
    done; (*b*)
    input'
  end


(* calculate the gradient of max_pool2d *)
let max_pool2d_backward padding input kernel stride output' =
  let max_pool = ref 0. in
  let init_pool_fun = (fun () -> max_pool := Stdlib.min_float) in
  let add_val_pool_fun =
    (fun v -> max_pool := Stdlib.max !max_pool v)
  in
  let end_pool_fun = (fun () -> !max_pool) in
  let compute_grad_fun = (fun input_val input_grad output_val output_grad ->
      if ((Scalar.abs (input_val -. output_val)) < 1e-8) (*TODO: change comparison here *)
      then input_grad +. output_grad
      else input_grad
    ) in
  (_pool2d_backward padding input kernel stride output'
     init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun)


(* calculate the gradient of avg_pool2d *)
let avg_pool2d_backward padding input kernel stride output' =
  let sum_pool = ref 0. in
  let cnt = ref 0. in
  let init_pool_fun = (fun () -> (sum_pool := 0.; cnt := 0.)) in
  let add_val_pool_fun =
    (fun v -> sum_pool := !sum_pool +. v; cnt := !cnt +. 1.)
  in
  let end_pool_fun = (fun () -> (!sum_pool /. !cnt)) in
  let compute_grad_fun =
    (fun _input_val input_grad _output_val output_grad ->
       input_grad +. output_grad /. !cnt)
  in
  (_pool2d_backward padding input kernel stride output'
     init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun)


(* TODO: definitely optimise *)
(* General function for avg_pool3d and max_pool3d *)
let _pool3d_backward _padding input kernel stride output'
    init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun =
  let p0 = (num_dims input = 5) in
  let p1 = (Array.length kernel = 3) in
  let p2 = (Array.length stride = 3) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 5)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 3)" (Array.length stride) in
    let s3 = Printf.sprintf "_pool3d_backward: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let input_dpts = input_shp.(3) in
  let in_channel = input_shp.(4) in

  let kernel_cols = kernel.(0) in
  let kernel_rows = kernel.(1) in
  let kernel_dpts = kernel.(2) in

  let col_stride = stride.(0) in
  let row_stride = stride.(1) in
  let dpt_stride = stride.(2) in

  let output_shp = shape output' in
  let output_cols = output_shp.(1) in
  let output_rows = output_shp.(2) in
  let output_dpts = output_shp.(3) in
  let p5 = (batches = output_shp.(0)) in
  let p6 = (in_channel = output_shp.(4)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Printf.sprintf "input shape is [%s]" s0 in
    let s3 = Printf.sprintf "output' shape is [%s]" s1 in
    let s4 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s5 = Printf.sprintf "the 5th dimension of input shape should be equal to the 5th dimension of output' shape" in
    let s6 = Printf.sprintf "_pool3d_backward: %s; %s; %s; %s." s2 s3 s4 s5 in
    Owl_exception.INVALID_ARGUMENT s6
  in
  Owl_exception.verify (p5 && p6) error;

  let (pad_top, pad_left, pad_shallow, _, _, _) =
    Owl_utils_infer_shape.calc_conv3d_padding
      input_cols input_rows input_dpts
      kernel_cols kernel_rows kernel_dpts
      output_cols output_rows output_dpts
      row_stride col_stride dpt_stride
  in
  let input' = zeros (kind input) (shape input) in
  begin
    for b = 0 to batches - 1 do
      for i = 0 to output_cols - 1 do
        for j = 0 to output_rows - 1 do
          for dpt = 0 to output_dpts - 1 do
            for k = 0 to in_channel - 1 do
              init_pool_fun ();

              for di = 0 to kernel_cols - 1 do
                for dj = 0 to kernel_rows - 1 do
                  for dk = 0 to kernel_dpts - 1 do
                    let in_col = i * col_stride + di - pad_left in
                    let in_row = j * row_stride + dj - pad_top in
                    let in_dpt = dpt * dpt_stride + dk - pad_shallow in
                    if ((0 <= in_col) && (in_col < input_cols) &&
                        (0 <= in_row) && (in_row < input_rows) &&
                        (0 <= in_dpt) && (in_dpt < input_dpts))
                    then add_val_pool_fun (get input [|b; in_col; in_row; in_dpt; k|])
                  done; (*dk*)
                done; (*dj*)
              done; (*di*)

              let output_val = end_pool_fun () in
              let output_grad = get output' [|b; i; j; dpt; k|] in
              for di = 0 to kernel_cols - 1 do
                for dj = 0 to kernel_rows - 1 do
                  for dk = 0 to kernel_dpts - 1 do
                    let in_col = i * col_stride + di - pad_left in
                    let in_row = j * row_stride + dj - pad_top in
                    let in_dpt = dpt * dpt_stride + dk - pad_shallow in
                    if ((0 <= in_col) && (in_col < input_cols) &&
                        (0 <= in_row) && (in_row < input_rows) &&
                        (0 <= in_dpt) && (in_dpt < input_dpts))
                    then
                      let input_val = (get input [|b; in_col; in_row; in_dpt; k|]) in
                      let input_grad = (get input' [|b; in_col; in_row; in_dpt; k|]) in
                      set input' [|b; in_col; in_row; in_dpt; k|]
                       (compute_grad_fun input_val input_grad output_val output_grad)
                  done; (*dk*)
                done; (*dj*)
              done; (*di*)

            done; (*k*)
          done; (*dpt*)
        done; (*j*)
      done; (*i*)
    done; (*b*)
    input'
  end


(* calculate the gradient of max_pool3d *)
let max_pool3d_backward padding input kernel stride output' =
  let max_pool = ref 0. in
  let init_pool_fun = (fun () -> max_pool := Stdlib.min_float) in
  let add_val_pool_fun =
    (fun v -> max_pool := Stdlib.max !max_pool v)
  in
  let end_pool_fun = (fun () -> !max_pool) in
  let compute_grad_fun = (fun input_val input_grad output_val output_grad ->
      if ((Scalar.abs (input_val -. output_val)) < 1e-8) (*TODO: change comparison here *)
      then input_grad +. output_grad
      else input_grad
    ) in
  (_pool3d_backward padding input kernel stride output'
     init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun)


(* calculate the gradient of avg_pool3d *)
let avg_pool3d_backward padding input kernel stride output' =
  let sum_pool = ref 0. in
  let cnt = ref 0. in
  let init_pool_fun = (fun () -> (sum_pool := 0.; cnt := 0.)) in
  let add_val_pool_fun =
    (fun v -> sum_pool := !sum_pool +. v; cnt := !cnt +. 1.)
  in
  let end_pool_fun = (fun () -> (!sum_pool /. !cnt)) in
  let compute_grad_fun =
    (fun _input_val input_grad _output_val output_grad ->
       input_grad +. output_grad /. !cnt)
  in
  (_pool3d_backward padding input kernel stride output'
     init_pool_fun add_val_pool_fun end_pool_fun compute_grad_fun)


(* calculate the gradient of max_pool1d *)
let max_pool1d_backward padding input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (Array.length kernel = 1) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 1)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "max_pool1d_backward: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = 1 in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_cols = kernel.(0) in
  let kernel_rows = 1 in
  let kernel = [|kernel_rows; kernel_cols|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let output_rows = 1 in
  let out_channel = output'_shp.(2) in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let input' = max_pool2d_backward padding input kernel stride output' in
  reshape input' input_shp


(* calculate the gradient of avg_pool1d *)
let avg_pool1d_backward padding input kernel stride output' =
  let p0 = (num_dims input = 3) in
  let p1 = (Array.length kernel = 1) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 1)" (Array.length kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "avg_pool1d_backward: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = 1 in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_cols = kernel.(0) in
  let kernel_rows = 1 in
  let kernel = [|kernel_rows; kernel_cols|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let output_rows = 1 in
  let out_channel = output'_shp.(2) in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let input' = avg_pool2d_backward padding input kernel stride output' in
  reshape input' input_shp


(* create a dilated 2d kernel *)
let upsample_kernel2d kernel rate =
  if rate = [|1; 1|] then kernel else (
    let kernel_shp  = shape kernel in
    let kernel_cols = kernel_shp.(0) in
    let kernel_rows = kernel_shp.(1) in
    let in_channel  = kernel_shp.(2) in
    let out_channel = kernel_shp.(3) in
    let col_rate    = rate.(0) in
    let row_rate    = rate.(1) in

    let col_up = kernel_cols + (kernel_cols - 1) * (col_rate - 1) in
    let row_up = kernel_rows + (kernel_rows - 1) * (row_rate - 1) in
    let new_kernel = zeros (kind kernel)
      [|col_up; row_up; in_channel; out_channel|] in

    for c = 0 to (kernel_cols - 1) do
      for r = 0 to (kernel_rows - 1) do
        for i = 0 to (in_channel - 1) do
          for o = 0 to (out_channel - 1) do
            let v = get kernel [|c; r; i; o|] in
            set new_kernel [|c * col_rate; r * row_rate; i; o|] v;
          done
        done
      done
    done;
    new_kernel
  )


(* change a dilated 2d kernel back to normal *)
let downsample_kernel2d kernel rate =
  if rate = [|1; 1|] then kernel else (
    let kernel_shp  = shape kernel in
    let kernel_cols = kernel_shp.(0) in
    let kernel_rows = kernel_shp.(1) in
    let in_channel  = kernel_shp.(2) in
    let out_channel = kernel_shp.(3) in
    let col_rate    = rate.(0) in
    let row_rate    = rate.(1) in

    let col_down = (kernel_cols + (col_rate - 1)) / col_rate in
    let row_down = (kernel_rows + (row_rate - 1)) / row_rate in
    let new_kernel = zeros (kind kernel)
      [|col_down; row_down; in_channel; out_channel|] in

    for c = 0 to (col_down - 1) do
      for r = 0 to (row_down - 1) do
        for i = 0 to (in_channel - 1) do
          for o = 0 to (out_channel - 1) do
            let v = get kernel [|c * col_rate; r * row_rate; i; o|] in
            set new_kernel [|c; r; i; o|] v
          done
        done
      done
    done;
    new_kernel
  )


(* dilated_conv2d: 4d input and 4d kernel, refer to tensorlfow doc
  input : [batch; input_column; input_row; input_channel]
  kernel: [kernel_column; kernel_row; input_channel; output_channel]
  stride: [column_stride; row_stride]
  rate  : [col_dilation_rate; row_dilation_rate]
  output: [batch; output_column; output_row; output_channel]
 *)
let dilated_conv2d ?(padding=SAME) input kernel stride rate =
  let p0 = (Array.length rate = 2) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 2)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv2d: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel = upsample_kernel2d kernel rate in
  conv2d ~padding input kernel stride


(* gradient of dilated_conv2d w.r.t the input *)
let dilated_conv2d_backward_input input kernel stride rate output' =
  let p0 = (Array.length rate = 2) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 2)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv2d_backward_input: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel = upsample_kernel2d kernel rate in
  conv2d_backward_input input kernel stride output'


(* gradient of dilated_conv2d w.r.t the kernel *)
let dilated_conv2d_backward_kernel input kernel stride rate output' =
  let p0 = (Array.length rate = 2) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 2)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv2d_backward_kernel: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel  = upsample_kernel2d kernel rate in
  let kernel' = conv2d_backward_kernel input kernel stride output' in
  downsample_kernel2d kernel' rate


(* create a dilated 3d kernel *)
let upsample_kernel3d kernel rate =
  if rate = [|1; 1; 1|] then kernel else (
    let kernel_shp  = shape kernel in
    let kernel_cols = kernel_shp.(0) in
    let kernel_rows = kernel_shp.(1) in
    let kernel_dpts = kernel_shp.(2) in
    let in_channel  = kernel_shp.(3) in
    let out_channel = kernel_shp.(4) in
    let col_rate    = rate.(0) in
    let row_rate    = rate.(1) in
    let dpt_rate    = rate.(2) in

    let col_up = kernel_cols + (kernel_cols - 1) * (col_rate - 1) in
    let row_up = kernel_rows + (kernel_rows - 1) * (row_rate - 1) in
    let dpt_up = kernel_dpts + (kernel_dpts - 1) * (dpt_rate - 1) in
    let new_kernel = zeros (kind kernel)
      [|col_up; row_up; dpt_up; in_channel; out_channel|] in

    for c = 0 to (kernel_cols - 1) do
      for r = 0 to (kernel_rows - 1) do
        for d = 0 to (kernel_dpts - 1) do
          for i = 0 to (in_channel - 1) do
            for o = 0 to (out_channel - 1) do
              let v = get kernel [|c; r; d; i; o|] in
              set new_kernel [|c * col_rate; r * row_rate; d * dpt_rate; i; o|] v;
            done
          done
        done
      done
    done;
    new_kernel
  )


(* change a dilated 3d kernel back to normal *)
let downsample_kernel3d kernel rate =
  if rate = [|1; 1; 1|] then kernel else (
    let kernel_shp  = shape kernel in
    let kernel_cols = kernel_shp.(0) in
    let kernel_rows = kernel_shp.(1) in
    let kernel_dpts = kernel_shp.(2) in
    let in_channel  = kernel_shp.(3) in
    let out_channel = kernel_shp.(4) in
    let col_rate    = rate.(0) in
    let row_rate    = rate.(1) in
    let dpt_rate    = rate.(2) in

    let col_down = (kernel_cols + (col_rate - 1)) / col_rate in
    let row_down = (kernel_rows + (row_rate - 1)) / row_rate in
    let dpt_down = (kernel_dpts + (dpt_rate - 1)) / dpt_rate in
    let new_kernel = zeros (kind kernel)
      [|col_down; row_down; dpt_down; in_channel; out_channel|] in

    for c = 0 to (col_down - 1) do
      for r = 0 to (row_down - 1) do
        for d = 0 to (dpt_down - 1) do
          for i = 0 to (in_channel - 1) do
            for o = 0 to (out_channel - 1) do
              let v = get kernel [|c * col_rate; r * row_rate; d * dpt_rate; i; o|] in
              set new_kernel [|c; r; d; i; o|] v
            done
          done
        done
      done
    done;
    new_kernel
  )


(* dilated_conv3d: 5d input and 5d kernel, refer to tensorflow doc
  input : [batch; input_column; input_row; input_depth; input_channel]
  kernel: [kernel_column; kernel_row; kernel_depth; input_channel; output_channel]
  stride: [column_stride; row_stride; depth_stride]
  rate  : [col_dilation_rate; row_dilation_rate; depth_dilation_rate]
  output: [batch; output_column; output_row; output_dpts; output_channel]
 *)
let dilated_conv3d ?(padding=SAME) input kernel stride rate =
  let p0 = (Array.length rate = 3) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 3)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv3d: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel = upsample_kernel3d kernel rate in
  conv3d ~padding input kernel stride


(* gradient of dilated_conv3d w.r.t the input *)
let dilated_conv3d_backward_input input kernel stride rate output' =
  let p0 = (Array.length rate = 3) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 3)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv3d_backward_input: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel = upsample_kernel3d kernel rate in
  conv3d_backward_input input kernel stride output'


(* gradient of dilated_conv3d w.r.t the kernel *)
let dilated_conv3d_backward_kernel input kernel stride rate output' =
  let p0 = (Array.length rate = 3) in
  let error () =
    let s0 = Printf.sprintf "rate dimension = %i (should be 3)" (Array.length rate) in
    let s1 = Printf.sprintf "dilated_conv3d_backward_kernel: %s." s0 in
    Owl_exception.INVALID_ARGUMENT s1
  in
  Owl_exception.verify p0 error;

  let kernel  = upsample_kernel3d kernel rate in
  let kernel' = conv3d_backward_kernel input kernel stride output' in
  downsample_kernel3d kernel' rate


(* dilated_conv1d: 3d input and 3d kernel, refer to tensorlfow doc
  input : [batch; input_column; input_channel]
  kernel: [kernel_column; input_channel; output_channel]
  stride: [column_rate]
  output: [batch; output_column; output_channel]
 *)
let dilated_conv1d ?(padding=SAME) input kernel stride rate =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s3 = Printf.sprintf "dilated_conv1d: %s; %s; %s." s0 s1 s2 in
    Owl_exception.INVALID_ARGUMENT s3
  in
  Owl_exception.verify (p0 && p1 && p2) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input = reshape input [|batches; 1; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p3 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3rd dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "dilated_conv1d: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p3 error;

  let kernel = reshape kernel [|1; kernel_cols; in_channel; out_channel|] in

  let col_stride = stride.(0) in
  let stride = [|1; col_stride|] in

  let output = dilated_conv2d ~padding input kernel stride rate in
  let output_shp = shape output in
  let output_cols = output_shp.(2) in
  let output = reshape output [|batches; output_cols; out_channel|] in
  output


(* gradient of dilated_conv1d w.r.t the input *)
let dilated_conv1d_backward_input input kernel stride rate output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "dilated_conv1d_backward_input: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "dilated_conv1d_backward_input: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "dilated_conv1d_backward_input: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let input' = dilated_conv2d_backward_input input kernel stride rate output' in
  reshape input' input_shp


(* gradient of dilated_conv1d w.r.t the kernel *)
let dilated_conv1d_backward_kernel input kernel stride rate output' =
  let p0 = (num_dims input = 3) in
  let p1 = (num_dims kernel = 3) in
  let p2 = (num_dims output' = 3) in
  let p3 = (Array.length stride = 1) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 3)" (num_dims input) in
    let s1 = Printf.sprintf "kernel dimension = %i (should be 3)" (num_dims kernel) in
    let s2 = Printf.sprintf "output' dimension = %i (should be 3)" (num_dims output') in
    let s3 = Printf.sprintf "stride dimension = %i (should be 1)" (Array.length stride) in
    let s4 = Printf.sprintf "dilated_conv1d_backward_kernel: %s; %s; %s; %s." s0 s1 s2 s3 in
    Owl_exception.INVALID_ARGUMENT s4
  in
  Owl_exception.verify (p0 && p1 && p2 && p3) error;

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let in_channel = input_shp.(2) in
  let input_rows = 1 in
  let input = reshape input [|batches; input_rows; input_cols; in_channel|] in

  let kernel_shp = shape kernel in
  let kernel_cols = kernel_shp.(0) in
  let out_channel = kernel_shp.(2) in
  let p4 = (in_channel = kernel_shp.(1)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Printf.sprintf "input shape is [%s]" s0 in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s4 = Printf.sprintf "the 3th dimension of input shape should be equal to the 2nd dimension of kernel shape" in
    let s5 = Printf.sprintf "dilated_conv1d_backward_kernel: %s, %s, %s." s1 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify p4 error;

  let kernel_rows = 1 in
  let kernel = reshape kernel [|kernel_rows; kernel_cols; in_channel; out_channel|] in

  let output'_shp = shape output' in
  let output_cols = output'_shp.(1) in
  let p5 = (batches = output'_shp.(0)) in
  let p6 = (out_channel = output'_shp.(2)) in

  let error () =
    let s0 = Owl_utils_array.to_string string_of_int input_shp in
    let s1 = Owl_utils_array.to_string string_of_int output'_shp in
    let s2 = Owl_utils_array.to_string string_of_int kernel_shp in
    let s3 = Printf.sprintf "input shape is [%s]" s0 in
    let s4 = Printf.sprintf "output' shape is [%s]" s1 in
    let s5 = Printf.sprintf "kernel shape is [%s]" s2 in
    let s6 = Printf.sprintf "the 1st dimension of input shape should be equal to the 1st dimension of output' shape" in
    let s7 = Printf.sprintf "the 3rd dimension of kernel shape should be equal to the 3rd dimension of output' shape" in
    let s8 = Printf.sprintf "dilated_conv1d_backward_kernel: %s; %s; %s; %s; %s." s3 s4 s5 s6 s7 in
    Owl_exception.INVALID_ARGUMENT s8
  in
  Owl_exception.verify (p5 && p6) error;

  let output_rows = 1 in
  let output' = reshape output' [|batches; output_rows; output_cols; out_channel|] in

  let col_stride = stride.(0) in
  let row_stride = 1 in
  let stride = [|row_stride; col_stride|] in

  let kernel' = dilated_conv2d_backward_kernel input kernel stride rate output' in
  reshape kernel' kernel_shp


let upsampling2d input size =
  let p0 = (num_dims input = 4) in
  let p1 = (Array.length size = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "size dimension = %i (should be 2)" (Array.length size) in
    let s2 = Printf.sprintf "upsampling2d: %s; %s." s0 s1 in
    Owl_exception.INVALID_ARGUMENT s2
  in
  Owl_exception.verify (p0 && p1) error;

  repeat input [|1; size.(0); size.(1); 1|]


let upsampling2d_backward input size output =
  let p0 = (num_dims input = 4) in
  let p1 = (Array.length size = 2) in

  let error () =
    let s0 = Printf.sprintf "input dimension = %i (should be 4)" (num_dims input) in
    let s1 = Printf.sprintf "size dimension = %i (should be 2)" (Array.length size) in
    let s2 = Printf.sprintf "upsampling2d_backward: %s; %s." s0 s1 in
    Owl_exception.INVALID_ARGUMENT s2
  in
  Owl_exception.verify (p0 && p1) error;

  let _kind = kind input in

  let input_shp = shape input in
  let batches = input_shp.(0) in
  let input_cols = input_shp.(1) in
  let input_rows = input_shp.(2) in
  let in_channel = input_shp.(3) in

  let col_scale = size.(0) in
  let row_scale = size.(1) in

  let output_shp = shape output in
  let output_cols = input_cols * col_scale in
  let output_rows = input_rows * row_scale in
  let p2 = (output_cols = output_shp.(1)) in
  let p3 = (output_rows = output_shp.(2)) in

  let error () =
    let s1 = Owl_utils_array.to_string string_of_int output_shp in
    let s2 = Printf.sprintf "output shape is [%s]" s1 in
    let s3 = Printf.sprintf "scaled output cols is %i, should be equal to the 2nd dimension of output shape" output_cols in
    let s4 = Printf.sprintf "scaled output rows is %i, should be equal to the 3rd dimension of output shape" output_rows in
    let s5 = Printf.sprintf "upsampling2d_backward: %s; %s; %s." s2 s3 s4 in
    Owl_exception.INVALID_ARGUMENT s5
  in
  Owl_exception.verify (p2 && p3) error;

  let input' = zeros _kind input_shp in

  for b = 0 to batches - 1 do
    for c = 0 to output_cols - 1 do
      let in_c = c / col_scale in
      let in_c = Stdlib.min in_c (input_cols - 1) in
      for r = 0 to output_rows - 1 do
        let in_r = r / row_scale in
        let in_r = Stdlib.min in_r (input_rows - 1) in
        for i = 0 to in_channel - 1 do
          let in_val = get input' [|b; in_c; in_r; i|] in
          let out_val = get output [|b; c; r; i|] in
          set input' [|b; in_c; in_r; i|] (in_val +. out_val)
        done
      done
    done
  done;

  input'


(* matrix functions *)

let _remove_unit_dims dims =
  let removed_ones_list = List.filter (fun x -> x > 1) (Array.to_list dims) in
  let not_empty_list = match removed_ones_list with
    | [] -> [1]
    | _ -> removed_ones_list
  in
  (Array.of_list not_empty_list)


let _check_is_matrix dims =
  if (Array.length dims) != 2
  then raise (Invalid_argument "The given NDarray is not a matrix!")
  else ()


let row_num varr =
  let dims = shape varr in
  (_check_is_matrix dims; dims.(0))


let col_num varr =
  let dims = shape varr in
  (_check_is_matrix dims; dims.(1))


(* NOTE: this is a view into the original array *)
let row varr ind =
  let dims = shape varr in
  (_check_is_matrix dims; Genarray.slice_left varr [|ind|])


let rows varr indices =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let new_rownum = Array.length indices in
  let new_colnum = dims.(1) in
  let new_varr = empty (kind varr) [|new_rownum; new_colnum|] in
  begin
    for i = 0 to new_rownum - 1 do
      Genarray.blit
        (Genarray.slice_left varr [|indices.(i)|]) (* indices[i] row of the original *)
        (Genarray.slice_left new_varr [|i|]) (* i-th row of the new matrix *)
    done;
    new_varr
  end


let copy_row_to vec varr ind =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  (Genarray.blit vec (Genarray.slice_left varr [|ind|]))


let copy_col_to vec varr ind =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let vec_dims = _remove_unit_dims(shape vec) in
  let vec_len =
    if (Array.length vec_dims) = 1
    then vec_dims.(0)
    else raise (Invalid_argument "Vector is not a column vector")
  in
  let num_rows = dims.(0) in
  let vec_linear = flatten vec |> array1_of_genarray in
  if num_rows != vec_len
  then raise (Invalid_argument "Column vector does not have the same length as the number of rows in the matrix")
  else
    begin
      for i = 0 to num_rows - 1 do
        Genarray.set varr [|i; ind|] (Array1.unsafe_get vec_linear i)
      done
    end


let dot varr_a varr_b =
  let (dims_a, dims_b) = (shape varr_a, shape varr_b) in
  let (_, _) = (_check_is_matrix dims_a, _check_is_matrix dims_b) in
  let m = dims_a.(0) in
  let cdim = dims_a.(1) in
  let n = dims_b.(1) in
  if (dims_b.(0)) != cdim
  then raise (Invalid_argument "Matrices cannot be multipled")
  else
    let varr_c = empty (kind varr_a) [|m; n|] in
    let sum = ref 0. in
    begin
      for i = 0 to m - 1 do
        for j = 0 to n - 1 do
          sum := 0.;
          for k = 0 to cdim - 1 do
            sum := !sum +. ((Genarray.get varr_a [|i; k|]) *. (Genarray.get varr_b [|k; j|]))
          done;
          Genarray.set varr_c [|i; j|] !sum
        done
      done;
      varr_c
    end


let trace varr =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let n = dims.(0) in
  if dims.(1) != n
  then raise (Invalid_argument "Argument is not a square matrix")
  else
    let sum = ref 0. in
    begin
      for i = 0 to n - 1 do
        sum := !sum +. (Genarray.get varr [|i; i|])
      done;
      !sum
    end


(* NOTE: each row is actually a view in the original matrix, no copying involved *)
let to_rows varr =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let m = dims.(0) in
  (Array.init m (fun i -> (Genarray.slice_left varr [|i|])))

let to_cols _harr = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.to_cols")

let of_rows rows =
  let m = Array.length rows in
  let row_dim = shape (rows.(0)) in
  let dims = Array.append [|m|] row_dim in
  let varr = empty (kind rows.(0)) dims in
  begin
    for i = 0 to m - 1 do
      Genarray.blit rows.(i) (Genarray.slice_left varr [|i|])
    done;
    varr
  end

let of_cols _cols = raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.of_cols")

let of_arrays kind arrays =
  let m = Array.length arrays in
  let n = Array.length (arrays.(0)) in
  let varr = empty kind [|m; n|] in
  begin
    for i = 0 to m - 1 do
      for j = 0 to n - 1 do
        Genarray.set varr [|i; j|] (Array.unsafe_get (arrays.(i)) j)
      done
    done;
    varr
  end


let draw_rows ?(replacement=true) varr count =
  let dims = shape varr in
  let indices = _draw_int_samples replacement (Array.length dims) count in
  let extracted = rows varr indices in
  (extracted, indices)


let draw_rows2 ?(replacement=true) varr_a varr_b count =
  let extracted_a, indices =
    draw_rows ~replacement:replacement varr_a count in
  let extracted_b = rows varr_b indices in
  (extracted_a, extracted_b, indices)


(* TODO: optimise and test *)
(*
 Implementing the following algorithm:
 http://www.irma-international.org/viewtitle/41011/ *)
let inv varr =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let n = Array.unsafe_get dims 0 in
  if (Array.unsafe_get dims 1) != n
  then failwith "no inverse - the matrix is not square"
  else
    let pivot_row = Array.make n 0. in
    let result_varr = copy varr in
    begin
      for p = 0 to n - 1 do
        let pivot_elem = get result_varr [|p; p|] in
        if get result_varr [|p; p|] = 0.
        then failwith "the matrix does not have an inverse";
        (* update elements of the pivot row, save old vals *)
        for j = 0 to n - 1 do
          pivot_row.(j) <- get result_varr [|p; j|];
          if j != p
          then set result_varr [|p; j|] (pivot_row.(j) /. pivot_elem)
        done;
        (* update elements of the pivot col *)
        for i = 0 to n - 1 do
          if i != p
          then set result_varr [|i; p|]
              ((get result_varr [|i; p|]) /. (~-. pivot_elem))
        done;
        (* update the rest of the matrix *)
        for i = 0 to n - 1 do
          let pivot_col_elem = get result_varr [|i; p|] in
          for j = 0 to n - 1 do
            if i != p && j != p
            then
              let pivot_row_elem = pivot_row.(j) in (* use old value *)
              let old_val = get result_varr [|i; j|] in
              let new_val = old_val +. (pivot_row_elem *. pivot_col_elem) in
              (set result_varr [|i; j|] new_val)
          done;
        done;
        (* update the pivot element *)
        set result_varr [|p; p|] (1. /. pivot_elem)
      done;
      result_varr
    end

let logdet _x =
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.logdet")

let qr _x =
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.qr")

let lq _x =
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.lq")

let chol ?(upper=true) _x =
  upper |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.chol")

let svd ?(thin=true) _x =
  thin |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.svd")

let sylvester _a _b _c =
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.sylvester")

let lyapunov _a _q =
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.lyapunov")

let discrete_lyapunov ?(solver=`default) _a _q =
  solver |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.discrete_lyapunov")

let linsolve ?(trans=false) ?(typ=`n) _a _b =
  trans |> ignore; typ |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.linsolve")

let care ?(diag_r = false)_a _b _q _r =
  diag_r |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.care")

let diag ?(k=0) _x =
  k |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.diag")

let diagm ?(k=0) _x =
  k |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.diagm")

let tril ?(k=0) _x =
  k |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.tril")

let triu ?(k=0) _x =
  k |> ignore;
  raise (Owl_exception.NOT_IMPLEMENTED "owl_base_dense_ndarray_generic.triu")

(* TODO: here k is not used, but neither is it in nonbase dense array? - investigate *)
let load _k f = Owl_io.marshal_from_file f


let max_rows varr =
  let dims = shape varr in
  let _ = _check_is_matrix dims in
  let r, c = dims.(0), dims.(1) in
  let result = Array.make r (0., 0, 0) in
  begin
    for i = 0 to r - 1 do
      let best = ref Stdlib.min_float in
      let best_pos = ref ~- 1 in
      for j = 0 to c - 1 do
        let x = get varr [|i; j|] in
        if (x > !best)
        then (best := x; best_pos := j)
      done;
      result.(i) <- (!best, i, !best_pos)
    done;
    result
  end

let one_hot _depth _x = failwith "Owl_base_dense_ndarray_generic:one_hot: not implemented"


(* Helper functions *)

let float_to_elt x = x

let elt_to_float x = x



(* ends here *)
OCaml

Innovation. Community. Security.