scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
//! Array manipulation operations similar to `NumPy`'s array manipulation routines
//!
//! This module provides functions for manipulating arrays, including flip, roll,
//! tile, repeat, and other operations, designed to mirror `NumPy`'s functionality.

use crate::ndarray_ext::reduction;
use crate::numeric::Float;
use crate::simd_ops::SimdUnifiedOps;
use ::ndarray::{Array, ArrayView, Ix1, Ix2};
use num_traits::Zero;

/// Result type for gradient function
pub type GradientResult<T> = Result<(Array<T, Ix2>, Array<T, Ix2>), &'static str>;

/// Flip a 2D array along one or more axes
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `flip_axis_0` - Whether to flip along axis 0 (rows)
/// * `flip_axis_0` - Whether to flip along axis 1 (columns)
///
/// # Returns
///
/// A new array with axes flipped as specified
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::flip_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6]];
///
/// // Flip along rows
/// let flipped_rows = flip_2d(a.view(), true, false);
/// assert_eq!(flipped_rows, array![[4, 5, 6], [1, 2, 3]]);
///
/// // Flip along columns
/// let flipped_cols = flip_2d(a.view(), false, true);
/// assert_eq!(flipped_cols, array![[3, 2, 1], [6, 5, 4]]);
///
/// // Flip along both axes
/// let flipped_both = flip_2d(a.view(), true, true);
/// assert_eq!(flipped_both, array![[6, 5, 4], [3, 2, 1]]);
/// ```
#[allow(dead_code)]
pub fn flip_2d<T>(array: ArrayView<T, Ix2>, flip_axis_0: bool, flipaxis_1: bool) -> Array<T, Ix2>
where
    T: Clone + Zero,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);
    let mut result = Array::<T, Ix2>::zeros((rows, cols));

    for i in 0..rows {
        for j in 0..cols {
            let src_i = if flip_axis_0 { rows - 1 - i } else { i };
            let src_j = if flipaxis_1 { cols - 1 - j } else { j };

            result[[i, j]] = array[[src_i, src_j]].clone();
        }
    }

    result
}

/// Roll array elements along one or both axes
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `shift_axis_0` - Number of places to shift along axis 0 (can be negative)
/// * `shift_axis_1` - Number of places to shift along axis 1 (can be negative)
///
/// # Returns
///
/// A new array with elements rolled as specified
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::roll_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6]];
///
/// // Roll along rows by 1
/// let rolled_rows = roll_2d(a.view(), 1, 0);
/// assert_eq!(rolled_rows, array![[4, 5, 6], [1, 2, 3]]);
///
/// // Roll along columns by -1
/// let rolled_cols = roll_2d(a.view(), 0, -1);
/// assert_eq!(rolled_cols, array![[2, 3, 1], [5, 6, 4]]);
/// ```
#[allow(dead_code)]
pub fn roll_2d<T>(
    array: ArrayView<T, Ix2>,
    shift_axis_0: isize,
    shift_axis_1: isize,
) -> Array<T, Ix2>
where
    T: Clone + Zero,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // Handle case where no shifting is needed
    if shift_axis_0 == 0 && shift_axis_1 == 0 {
        return array.to_owned();
    }

    // Calculate effective shifts (handle negative shifts and wrap around)
    let effective_shift_0 = if rows == 0 {
        0
    } else {
        ((shift_axis_0 % rows as isize) + rows as isize) % rows as isize
    };
    let effective_shift_1 = if cols == 0 {
        0
    } else {
        ((shift_axis_1 % cols as isize) + cols as isize) % cols as isize
    };

    let mut result = Array::<T, Ix2>::zeros((rows, cols));

    for i in 0..rows {
        for j in 0..cols {
            // Calculate source indices with wrapping
            let src_i = (i as isize + rows as isize - effective_shift_0) % rows as isize;
            let src_j = (j as isize + cols as isize - effective_shift_1) % cols as isize;

            result[[i, j]] = array[[src_i as usize, src_j as usize]].clone();
        }
    }

    result
}

/// Repeat an array by tiling it in multiple dimensions
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `reps_axis_0` - Number of times to repeat the array along axis 0
/// * `reps_axis_1` - Number of times to repeat the array along axis 1
///
/// # Returns
///
/// A new array formed by repeating the input array
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::tile_2d;
///
/// let a = array![[1, 2], [3, 4]];
///
/// // Tile array to repeat it 2 times along axis 0 and 3 times along axis 1
/// let tiled = tile_2d(a.view(), 2, 3);
/// assert_eq!(tiled.shape(), &[4, 6]);
/// assert_eq!(tiled,
///     array![
///         [1, 2, 1, 2, 1, 2],
///         [3, 4, 3, 4, 3, 4],
///         [1, 2, 1, 2, 1, 2],
///         [3, 4, 3, 4, 3, 4]
///     ]
/// );
/// ```
#[allow(dead_code)]
pub fn tile_2d<T>(array: ArrayView<T, Ix2>, reps_axis_0: usize, repsaxis_1: usize) -> Array<T, Ix2>
where
    T: Clone + Default + Zero,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // New dimensions after tiling
    let new_rows = rows * reps_axis_0;
    let new_cols = cols * repsaxis_1;

    // Edge case - zero repetitions
    if reps_axis_0 == 0 || repsaxis_1 == 0 {
        return Array::<T, Ix2>::default((0, 0));
    }

    // Edge case - one repetition
    if reps_axis_0 == 1 && repsaxis_1 == 1 {
        return array.to_owned();
    }

    let mut result = Array::<T, Ix2>::zeros((new_rows, new_cols));

    // Fill the result with repeated copies of the array
    for i in 0..new_rows {
        for j in 0..new_cols {
            let src_i = i % rows;
            let src_j = j % cols;

            result[[i, j]] = array[[src_i, src_j]].clone();
        }
    }

    result
}

/// Repeat array elements by duplicating values
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `repeats_axis_0` - Number of times to repeat each element along axis 0
/// * `repeats_axis_1` - Number of times to repeat each element along axis 1
///
/// # Returns
///
/// A new array with elements repeated as specified
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::repeat_2d;
///
/// let a = array![[1, 2], [3, 4]];
///
/// // Repeat array elements 2 times along axis 0 and 3 times along axis 1
/// let repeated = repeat_2d(a.view(), 2, 3);
/// assert_eq!(repeated.shape(), &[4, 6]);
/// assert_eq!(repeated,
///     array![
///         [1, 1, 1, 2, 2, 2],
///         [1, 1, 1, 2, 2, 2],
///         [3, 3, 3, 4, 4, 4],
///         [3, 3, 3, 4, 4, 4]
///     ]
/// );
/// ```
#[allow(dead_code)]
pub fn repeat_2d<T>(
    array: ArrayView<T, Ix2>,
    repeats_axis_0: usize,
    repeats_axis_1: usize,
) -> Array<T, Ix2>
where
    T: Clone + Default + Zero,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // New dimensions after repeating
    let new_rows = rows * repeats_axis_0;
    let new_cols = cols * repeats_axis_1;

    // Edge case - zero repetitions
    if repeats_axis_0 == 0 || repeats_axis_1 == 0 {
        return Array::<T, Ix2>::default((0, 0));
    }

    // Edge case - one repetition
    if repeats_axis_0 == 1 && repeats_axis_1 == 1 {
        return array.to_owned();
    }

    let mut result = Array::<T, Ix2>::zeros((new_rows, new_cols));

    // Fill the result with repeated elements
    for i in 0..rows {
        for j in 0..cols {
            for i_rep in 0..repeats_axis_0 {
                for j_rep in 0..repeats_axis_1 {
                    let dest_i = i * repeats_axis_0 + i_rep;
                    let dest_j = j * repeats_axis_1 + j_rep;

                    result[[dest_i, dest_j]] = array[[i, j]].clone();
                }
            }
        }
    }

    result
}

/// Swap rows or columns in a 2D array
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `index1` - First index to swap
/// * `index2` - Second index to swap
/// * `axis` - Axis along which to swap (0 for rows, 1 for columns)
///
/// # Returns
///
/// A new array with specified rows or columns swapped
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::swap_axes_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
///
/// // Swap rows 0 and 2
/// let swapped_rows = swap_axes_2d(a.view(), 0, 2, 0).expect("Operation failed");
/// assert_eq!(swapped_rows, array![[7, 8, 9], [4, 5, 6], [1, 2, 3]]);
///
/// // Swap columns 0 and 1
/// let swapped_cols = swap_axes_2d(a.view(), 0, 1, 1).expect("Operation failed");
/// assert_eq!(swapped_cols, array![[2, 1, 3], [5, 4, 6], [8, 7, 9]]);
/// ```
#[allow(dead_code)]
pub fn swap_axes_2d<T>(
    array: ArrayView<T, Ix2>,
    index1: usize,
    index2: usize,
    axis: usize,
) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if axis > 1 {
        return Err("Axis must be 0 or 1 for 2D arrays");
    }

    // Check indices are in bounds
    let axis_len = if axis == 0 { rows } else { cols };
    if index1 >= axis_len || index2 >= axis_len {
        return Err("Indices out of bounds");
    }

    // If indices are the same, just clone the array
    if index1 == index2 {
        return Ok(array.to_owned());
    }

    let mut result = array.to_owned();

    match axis {
        0 => {
            // Swap rows
            for j in 0..cols {
                let temp = result[[index1, j]].clone();
                result[[index1, j]] = result[[index2, j]].clone();
                result[[index2, j]] = temp;
            }
        }
        1 => {
            // Swap columns
            for i in 0..rows {
                let temp = result[[i, index1]].clone();
                result[[i, index1]] = result[[i, index2]].clone();
                result[[i, index2]] = temp;
            }
        }
        _ => unreachable!(),
    }

    Ok(result)
}

/// Pad a 2D array with a constant value
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `pad_width` - A tuple of tuples specifying the number of values padded
///   to the edges of each axis: ((before_axis_0, after_axis_0), (before_axis_1, after_axis_1))
/// * `pad_value` - The value to set the padded elements
///
/// # Returns
///
/// A new array with padded borders
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::pad_2d;
///
/// let a = array![[1, 2], [3, 4]];
///
/// // Pad with 1 row before, 2 rows after, 1 column before, and 0 columns after
/// let padded = pad_2d(a.view(), ((1, 2), (1, 0)), 0);
/// assert_eq!(padded.shape(), &[5, 3]);
/// assert_eq!(padded,
///     array![
///         [0, 0, 0],
///         [0, 1, 2],
///         [0, 3, 4],
///         [0, 0, 0],
///         [0, 0, 0]
///     ]
/// );
/// ```
#[allow(dead_code)]
pub fn pad_2d<T>(
    array: ArrayView<T, Ix2>,
    pad_width: ((usize, usize), (usize, usize)),
    pad_value: T,
) -> Array<T, Ix2>
where
    T: Clone,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);
    let ((before_0, after_0), (before_1, after_1)) = pad_width;

    // Calculate new dimensions
    let new_rows = rows + before_0 + after_0;
    let new_cols = cols + before_1 + after_1;

    // Create the result array filled with the padding value
    let mut result = Array::<T, Ix2>::from_elem((new_rows, new_cols), pad_value);

    // Copy the original array into the padded array
    for i in 0..rows {
        for j in 0..cols {
            result[[i + before_0, j + before_1]] = array[[i, j]].clone();
        }
    }

    result
}

/// Concatenate 2D arrays along a specified axis
///
/// # Arguments
///
/// * `arrays` - A slice of 2D arrays to concatenate
/// * `axis` - The axis along which to concatenate (0 for rows, 1 for columns)
///
/// # Returns
///
/// A new array containing the concatenated arrays
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::concatenate_2d;
///
/// let a = array![[1, 2], [3, 4]];
/// let b = array![[5, 6], [7, 8]];
///
/// // Concatenate along rows (vertically)
/// let vertical = concatenate_2d(&[a.view(), b.view()], 0).expect("Operation failed");
/// assert_eq!(vertical.shape(), &[4, 2]);
/// assert_eq!(vertical, array![[1, 2], [3, 4], [5, 6], [7, 8]]);
///
/// // Concatenate along columns (horizontally)
/// let horizontal = concatenate_2d(&[a.view(), b.view()], 1).expect("Operation failed");
/// assert_eq!(horizontal.shape(), &[2, 4]);
/// assert_eq!(horizontal, array![[1, 2, 5, 6], [3, 4, 7, 8]]);
/// ```
#[allow(dead_code)]
pub fn concatenate_2d<T>(
    arrays: &[ArrayView<T, Ix2>],
    axis: usize,
) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone + Zero,
{
    if arrays.is_empty() {
        return Err("No arrays provided for concatenation");
    }

    if axis > 1 {
        return Err("Axis must be 0 or 1 for 2D arrays");
    }

    // Get the shape of the first array as a reference
    let firstshape = arrays[0].shape();

    // Calculate the total shape after concatenation
    let mut totalshape = [firstshape[0], firstshape[1]];
    for array in arrays.iter().skip(1) {
        let currentshape = array.shape();

        // Ensure all arrays have compatible shapes
        if axis == 0 && currentshape[1] != firstshape[1] {
            return Err("All arrays must have the same number of columns for axis=0 concatenation");
        } else if axis == 1 && currentshape[0] != firstshape[0] {
            return Err("All arrays must have the same number of rows for axis=1 concatenation");
        }

        totalshape[axis] += currentshape[axis];
    }

    // Create the result array
    let mut result = Array::<T, Ix2>::zeros((totalshape[0], totalshape[1]));

    // Fill the result array with data from the input arrays
    match axis {
        0 => {
            // Concatenate along axis 0 (vertically)
            let mut row_offset = 0;
            for array in arrays {
                let rows = array.shape()[0];
                let cols = array.shape()[1];

                for i in 0..rows {
                    for j in 0..cols {
                        result[[row_offset + i, j]] = array[[i, j]].clone();
                    }
                }

                row_offset += rows;
            }
        }
        1 => {
            // Concatenate along axis 1 (horizontally)
            let mut col_offset = 0;
            for array in arrays {
                let rows = array.shape()[0];
                let cols = array.shape()[1];

                for i in 0..rows {
                    for j in 0..cols {
                        result[[i, col_offset + j]] = array[[i, j]].clone();
                    }
                }

                col_offset += cols;
            }
        }
        _ => unreachable!(),
    }

    Ok(result)
}

/// Stack a sequence of 1D arrays into a 2D array
///
/// # Arguments
///
/// * `arrays` - A slice of 1D arrays to stack
///
/// # Returns
///
/// A 2D array where each row contains an input array
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::vstack_1d;
///
/// let a = array![1, 2, 3];
/// let b = array![4, 5, 6];
/// let c = array![7, 8, 9];
///
/// let stacked = vstack_1d(&[a.view(), b.view(), c.view()]).expect("Operation failed");
/// assert_eq!(stacked.shape(), &[3, 3]);
/// assert_eq!(stacked, array![[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
/// ```
#[allow(dead_code)]
pub fn vstack_1d<T>(arrays: &[ArrayView<T, Ix1>]) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone + Zero,
{
    if arrays.is_empty() {
        return Err("No arrays provided for stacking");
    }

    // All arrays must have the same length
    let expected_len = arrays[0].len();
    for (_i, array) in arrays.iter().enumerate().skip(1) {
        if array.len() != expected_len {
            return Err("Arrays must have consistent lengths for stacking");
        }
    }

    // Create the result array
    let rows = arrays.len();
    let cols = expected_len;
    let mut result = Array::<T, Ix2>::zeros((rows, cols));

    // Fill the result array
    for (i, array) in arrays.iter().enumerate() {
        for (j, val) in array.iter().enumerate() {
            result[[i, j]] = val.clone();
        }
    }

    Ok(result)
}

/// Stack a sequence of 1D arrays horizontally (as columns) into a 2D array
///
/// # Arguments
///
/// * `arrays` - A slice of 1D arrays to stack
///
/// # Returns
///
/// A 2D array where each column contains an input array
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::hstack_1d;
///
/// let a = array![1, 2, 3];
/// let b = array![4, 5, 6];
///
/// let stacked = hstack_1d(&[a.view(), b.view()]).expect("Operation failed");
/// assert_eq!(stacked.shape(), &[3, 2]);
/// assert_eq!(stacked, array![[1, 4], [2, 5], [3, 6]]);
/// ```
#[allow(dead_code)]
pub fn hstack_1d<T>(arrays: &[ArrayView<T, Ix1>]) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone + Zero,
{
    if arrays.is_empty() {
        return Err("No arrays provided for stacking");
    }

    // All arrays must have the same length
    let expected_len = arrays[0].len();
    for (_i, array) in arrays.iter().enumerate().skip(1) {
        if array.len() != expected_len {
            return Err("Arrays must have consistent lengths for stacking");
        }
    }

    // Create the result array
    let rows = expected_len;
    let cols = arrays.len();
    let mut result = Array::<T, Ix2>::zeros((rows, cols));

    // Fill the result array
    for (j, array) in arrays.iter().enumerate() {
        for (i, val) in array.iter().enumerate() {
            result[[i, j]] = val.clone();
        }
    }

    Ok(result)
}

/// Remove a dimension of size 1 from a 2D array, resulting in a 1D array
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `axis` - The axis to squeeze (0 for rows, 1 for columns)
///
/// # Returns
///
/// A 1D array with the specified dimension removed
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::squeeze_2d;
///
/// let a = array![[1, 2, 3]];  // 1x3 array (1 row, 3 columns)
/// let b = array![[1], [2], [3]];  // 3x1 array (3 rows, 1 column)
///
/// // Squeeze out the row dimension (axis 0) from a
/// let squeezed_a = squeeze_2d(a.view(), 0).expect("Operation failed");
/// assert_eq!(squeezed_a.shape(), &[3]);
/// assert_eq!(squeezed_a, array![1, 2, 3]);
///
/// // Squeeze out the column dimension (axis 1) from b
/// let squeezed_b = squeeze_2d(b.view(), 1).expect("Operation failed");
/// assert_eq!(squeezed_b.shape(), &[3]);
/// assert_eq!(squeezed_b, array![1, 2, 3]);
/// ```
#[allow(dead_code)]
pub fn squeeze_2d<T>(array: ArrayView<T, Ix2>, axis: usize) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Zero,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    match axis {
        0 => {
            // Squeeze out row dimension
            if rows != 1 {
                return Err("Cannot squeeze array with more than 1 row along axis 0");
            }

            let mut result = Array::<T, Ix1>::zeros(cols);
            for j in 0..cols {
                result[j] = array[[0, j]].clone();
            }

            Ok(result)
        }
        1 => {
            // Squeeze out column dimension
            if cols != 1 {
                return Err("Cannot squeeze array with more than 1 column along axis 1");
            }

            let mut result = Array::<T, Ix1>::zeros(rows);
            for i in 0..rows {
                result[i] = array[[i, 0]].clone();
            }

            Ok(result)
        }
        _ => Err("Axis must be 0 or 1 for 2D arrays"),
    }
}

/// Create a meshgrid from 1D coordinate arrays
///
/// # Arguments
///
/// * `x` - 1D array of x coordinates
/// * `y` - 1D array of y coordinates
///
/// # Returns
///
/// A tuple of two 2D arrays (X, Y) where X and Y are copies of the input arrays
/// repeated to form a meshgrid
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::meshgrid;
///
/// let x = array![1, 2, 3];
/// let y = array![4, 5];
/// let (x_grid, y_grid) = meshgrid(x.view(), y.view()).expect("Operation failed");
/// assert_eq!(x_grid.shape(), &[2, 3]);
/// assert_eq!(y_grid.shape(), &[2, 3]);
/// assert_eq!(x_grid, array![[1, 2, 3], [1, 2, 3]]);
/// assert_eq!(y_grid, array![[4, 4, 4], [5, 5, 5]]);
/// ```
#[allow(dead_code)]
pub fn meshgrid<T>(x: ArrayView<T, Ix1>, y: ArrayView<T, Ix1>) -> GradientResult<T>
where
    T: Clone + Zero,
{
    let nx = x.len();
    let ny = y.len();

    if nx == 0 || ny == 0 {
        return Err("Input arrays must not be empty");
    }

    // Create output arrays
    let mut x_grid = Array::<T, Ix2>::zeros((ny, nx));
    let mut y_grid = Array::<T, Ix2>::zeros((ny, nx));

    // Fill the meshgrid
    for i in 0..ny {
        for j in 0..nx {
            x_grid[[i, j]] = x[j].clone();
            y_grid[[i, j]] = y[i].clone();
        }
    }

    Ok((x_grid, y_grid))
}

/// Find unique elements in an array
///
/// # Arguments
///
/// * `array` - The input 1D array
///
/// # Returns
///
/// A 1D array containing the unique elements of the input array, sorted
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::unique;
///
/// let a = array![3, 1, 2, 2, 3, 4, 1];
/// let result = unique(a.view()).expect("Operation failed");
/// assert_eq!(result, array![1, 2, 3, 4]);
/// ```
#[allow(dead_code)]
pub fn unique<T>(array: ArrayView<T, Ix1>) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Ord,
{
    if array.is_empty() {
        return Err("Input array must not be empty");
    }

    // Clone elements to a Vec and sort
    let mut values: Vec<T> = array.iter().cloned().collect();
    values.sort();

    // Remove duplicates
    values.dedup();

    // Convert to ndarray
    Ok(Array::from_vec(values))
}

/// Return the indices of the minimum values along the specified axis
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `axis` - The axis along which to find the minimum values (0 for rows, 1 for columns, None for flattened array)
///
/// # Returns
///
/// A 1D array containing the indices of the minimum values
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::argmin;
///
/// let a = array![[5, 2, 3], [4, 1, 6]];
///
/// // Find indices of minimum values along axis 0 (columns)
/// let result = argmin(a.view(), Some(0)).expect("Operation failed");
/// assert_eq!(result, array![1, 1, 0]); // The indices of min values in each column
///
/// // Find indices of minimum values along axis 1 (rows)
/// let result = argmin(a.view(), Some(1)).expect("Operation failed");
/// assert_eq!(result, array![1, 1]); // The indices of min values in each row
///
/// // Find index of minimum value in flattened array
/// let result = argmin(a.view(), None).expect("Operation failed");
/// assert_eq!(result[0], 4); // The index of the minimum value in the flattened array (row 1, col 1)
/// ```
#[allow(dead_code)]
pub fn argmin<T>(
    array: ArrayView<T, Ix2>,
    axis: Option<usize>,
) -> Result<Array<usize, Ix1>, &'static str>
where
    T: Clone + PartialOrd,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if rows == 0 || cols == 0 {
        return Err("Input array must not be empty");
    }

    match axis {
        Some(0) => {
            // Find min indices along axis 0 (for each column)
            let mut indices = Array::<usize, Ix1>::zeros(cols);

            for j in 0..cols {
                let mut min_idx = 0;
                let mut min_val = &array[[0, j]];

                for i in 1..rows {
                    if &array[[i, j]] < min_val {
                        min_idx = i;
                        min_val = &array[[i, j]];
                    }
                }

                indices[j] = min_idx;
            }

            Ok(indices)
        }
        Some(1) => {
            // Find min indices along axis 1 (for each row)
            let mut indices = Array::<usize, Ix1>::zeros(rows);

            for i in 0..rows {
                let mut min_idx = 0;
                let mut min_val = &array[[i, 0]];

                for j in 1..cols {
                    if &array[[i, j]] < min_val {
                        min_idx = j;
                        min_val = &array[[i, j]];
                    }
                }

                indices[i] = min_idx;
            }

            Ok(indices)
        }
        Some(_) => Err("Axis must be 0 or 1 for 2D arrays"),
        None => {
            // Find min index in flattened array
            let mut min_idx = 0;
            let mut min_val = &array[[0, 0]];

            for i in 0..rows {
                for j in 0..cols {
                    if &array[[i, j]] < min_val {
                        min_idx = i * cols + j;
                        min_val = &array[[i, j]];
                    }
                }
            }

            Ok(Array::from_vec(vec![min_idx]))
        }
    }
}

/// Return the indices of the minimum values along the specified axis with SIMD acceleration.
///
/// This is a SIMD-accelerated version of `argmin` that provides significant performance
/// improvements for large arrays (typically 2-3x faster for f32 operations).
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `axis` - The axis along which to find the minimum values (0 for rows, 1 for columns, None for flattened array)
///
/// # Returns
///
/// A 1D array containing the indices of the minimum values
///
/// # Performance
///
/// - For axis=None (flattened): Uses SIMD for f32/f64 types, ~2-3x faster
/// - For axis=Some(0/1): Currently uses scalar implementation
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::argmin_simd;
///
/// let a = array![[5.0f32, 2.0, 3.0], [4.0, 1.0, 6.0]];
///
/// // Find index of minimum value in flattened array (SIMD-accelerated)
/// let result = argmin_simd(a.view(), None).expect("Operation failed");
/// assert_eq!(result[0], 4); // Index of 1.0 in flattened array
/// ```
#[allow(dead_code)]
pub fn argmin_simd<T>(
    array: ArrayView<T, Ix2>,
    axis: Option<usize>,
) -> Result<Array<usize, Ix1>, &'static str>
where
    T: Clone + PartialOrd + Float + SimdUnifiedOps,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if rows == 0 || cols == 0 {
        return Err("Input array must not be empty");
    }

    match axis {
        Some(0) => {
            // Find min indices along axis 0 (for each column)
            let mut indices = Array::<usize, Ix1>::zeros(cols);

            for j in 0..cols {
                // Extract column as contiguous 1D array for SIMD
                let col = array.column(j);
                if col.is_standard_layout() {
                    // Can use SIMD on contiguous column
                    if let Some(idx) = reduction::argmin_simd(&col) {
                        indices[j] = idx;
                    }
                } else {
                    // Fallback to scalar for non-contiguous
                    let mut min_idx = 0;
                    let mut min_val = &array[[0, j]];

                    for i in 1..rows {
                        if &array[[i, j]] < min_val {
                            min_idx = i;
                            min_val = &array[[i, j]];
                        }
                    }

                    indices[j] = min_idx;
                }
            }

            Ok(indices)
        }
        Some(1) => {
            // Find min indices along axis 1 (for each row)
            let mut indices = Array::<usize, Ix1>::zeros(rows);

            for i in 0..rows {
                // Extract row as contiguous 1D array for SIMD
                let row = array.row(i);
                if row.is_standard_layout() {
                    // Can use SIMD on contiguous row
                    if let Some(idx) = reduction::argmin_simd(&row) {
                        indices[i] = idx;
                    }
                } else {
                    // Fallback to scalar for non-contiguous
                    let mut min_idx = 0;
                    let mut min_val = &array[[i, 0]];

                    for j in 1..cols {
                        if &array[[i, j]] < min_val {
                            min_idx = j;
                            min_val = &array[[i, j]];
                        }
                    }

                    indices[i] = min_idx;
                }
            }

            Ok(indices)
        }
        Some(_) => Err("Axis must be 0 or 1 for 2D arrays"),
        None => {
            // Find min index in flattened array with SIMD
            // Flatten to 1D for SIMD processing
            let flattened = array.as_slice();

            if let Some(slice) = flattened {
                // Contiguous memory - can use SIMD directly
                let view = crate::ndarray::ArrayView1::from(slice);
                if let Some(idx) = reduction::argmin_simd(&view) {
                    return Ok(Array::from_vec(vec![idx]));
                }
            }

            // Fallback to scalar for non-contiguous arrays
            let mut min_idx = 0;
            let mut min_val = &array[[0, 0]];

            for i in 0..rows {
                for j in 0..cols {
                    if &array[[i, j]] < min_val {
                        min_idx = i * cols + j;
                        min_val = &array[[i, j]];
                    }
                }
            }

            Ok(Array::from_vec(vec![min_idx]))
        }
    }
}

/// Return the indices of the maximum values along the specified axis
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `axis` - The axis along which to find the maximum values (0 for rows, 1 for columns, None for flattened array)
///
/// # Returns
///
/// A 1D array containing the indices of the maximum values
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::argmax;
///
/// let a = array![[5, 2, 3], [4, 1, 6]];
///
/// // Find indices of maximum values along axis 0 (columns)
/// let result = argmax(a.view(), Some(0)).expect("Operation failed");
/// assert_eq!(result, array![0, 0, 1]); // The indices of max values in each column
///
/// // Find indices of maximum values along axis 1 (rows)
/// let result = argmax(a.view(), Some(1)).expect("Operation failed");
/// assert_eq!(result, array![0, 2]); // The indices of max values in each row
///
/// // Find index of maximum value in flattened array
/// let result = argmax(a.view(), None).expect("Operation failed");
/// assert_eq!(result[0], 5); // The index of the maximum value in the flattened array (row 1, col 2)
/// ```
#[allow(dead_code)]
pub fn argmax<T>(
    array: ArrayView<T, Ix2>,
    axis: Option<usize>,
) -> Result<Array<usize, Ix1>, &'static str>
where
    T: Clone + PartialOrd,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if rows == 0 || cols == 0 {
        return Err("Input array must not be empty");
    }

    match axis {
        Some(0) => {
            // Find max indices along axis 0 (for each column)
            let mut indices = Array::<usize, Ix1>::zeros(cols);

            for j in 0..cols {
                let mut max_idx = 0;
                let mut max_val = &array[[0, j]];

                for i in 1..rows {
                    if &array[[i, j]] > max_val {
                        max_idx = i;
                        max_val = &array[[i, j]];
                    }
                }

                indices[j] = max_idx;
            }

            Ok(indices)
        }
        Some(1) => {
            // Find max indices along axis 1 (for each row)
            let mut indices = Array::<usize, Ix1>::zeros(rows);

            for i in 0..rows {
                let mut max_idx = 0;
                let mut max_val = &array[[i, 0]];

                for j in 1..cols {
                    if &array[[i, j]] > max_val {
                        max_idx = j;
                        max_val = &array[[i, j]];
                    }
                }

                indices[i] = max_idx;
            }

            Ok(indices)
        }
        Some(_) => Err("Axis must be 0 or 1 for 2D arrays"),
        None => {
            // Find max index in flattened array
            let mut max_idx = 0;
            let mut max_val = &array[[0, 0]];

            for i in 0..rows {
                for j in 0..cols {
                    if &array[[i, j]] > max_val {
                        max_idx = i * cols + j;
                        max_val = &array[[i, j]];
                    }
                }
            }

            Ok(Array::from_vec(vec![max_idx]))
        }
    }
}

/// Return the indices of the maximum values along the specified axis with SIMD acceleration.
///
/// This is a SIMD-accelerated version of `argmax` that provides significant performance
/// improvements for large arrays (typically 2-3x faster for f32 operations).
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `axis` - The axis along which to find the maximum values (0 for rows, 1 for columns, None for flattened array)
///
/// # Returns
///
/// A 1D array containing the indices of the maximum values
///
/// # Performance
///
/// - For axis=None (flattened): Uses SIMD for f32/f64 types, ~2-3x faster
/// - For axis=Some(0/1): Uses SIMD when rows/columns are contiguous in memory
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::argmax_simd;
///
/// let a = array![[5.0f32, 2.0, 3.0], [4.0, 1.0, 6.0]];
///
/// // Find index of maximum value in flattened array (SIMD-accelerated)
/// let result = argmax_simd(a.view(), None).expect("Operation failed");
/// assert_eq!(result[0], 5); // Index of 6.0 in flattened array
/// ```
#[allow(dead_code)]
pub fn argmax_simd<T>(
    array: ArrayView<T, Ix2>,
    axis: Option<usize>,
) -> Result<Array<usize, Ix1>, &'static str>
where
    T: Clone + PartialOrd + Float + SimdUnifiedOps,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if rows == 0 || cols == 0 {
        return Err("Input array must not be empty");
    }

    match axis {
        Some(0) => {
            // Find max indices along axis 0 (for each column)
            let mut indices = Array::<usize, Ix1>::zeros(cols);

            for j in 0..cols {
                // Extract column as contiguous 1D array for SIMD
                let col = array.column(j);
                if col.is_standard_layout() {
                    // Can use SIMD on contiguous column
                    if let Some(idx) = reduction::argmax_simd(&col) {
                        indices[j] = idx;
                    }
                } else {
                    // Fallback to scalar for non-contiguous
                    let mut max_idx = 0;
                    let mut max_val = &array[[0, j]];

                    for i in 1..rows {
                        if &array[[i, j]] > max_val {
                            max_idx = i;
                            max_val = &array[[i, j]];
                        }
                    }

                    indices[j] = max_idx;
                }
            }

            Ok(indices)
        }
        Some(1) => {
            // Find max indices along axis 1 (for each row)
            let mut indices = Array::<usize, Ix1>::zeros(rows);

            for i in 0..rows {
                // Extract row as contiguous 1D array for SIMD
                let row = array.row(i);
                if row.is_standard_layout() {
                    // Can use SIMD on contiguous row
                    if let Some(idx) = reduction::argmax_simd(&row) {
                        indices[i] = idx;
                    }
                } else {
                    // Fallback to scalar for non-contiguous
                    let mut max_idx = 0;
                    let mut max_val = &array[[i, 0]];

                    for j in 1..cols {
                        if &array[[i, j]] > max_val {
                            max_idx = j;
                            max_val = &array[[i, j]];
                        }
                    }

                    indices[i] = max_idx;
                }
            }

            Ok(indices)
        }
        Some(_) => Err("Axis must be 0 or 1 for 2D arrays"),
        None => {
            // Find max index in flattened array with SIMD
            // Flatten to 1D for SIMD processing
            let flattened = array.as_slice();

            if let Some(slice) = flattened {
                // Contiguous memory - can use SIMD directly
                let view = crate::ndarray::ArrayView1::from(slice);
                if let Some(idx) = reduction::argmax_simd(&view) {
                    return Ok(Array::from_vec(vec![idx]));
                }
            }

            // Fallback to scalar for non-contiguous arrays
            let mut max_idx = 0;
            let mut max_val = &array[[0, 0]];

            for i in 0..rows {
                for j in 0..cols {
                    if &array[[i, j]] > max_val {
                        max_idx = i * cols + j;
                        max_val = &array[[i, j]];
                    }
                }
            }

            Ok(Array::from_vec(vec![max_idx]))
        }
    }
}

/// Calculate the gradient of an array
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `spacing` - Optional tuple of spacings for each axis
///
/// # Returns
///
/// A tuple of arrays (grad_y, grad_x) containing the gradient along each axis
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::manipulation::gradient;
///
/// let a = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
///
/// // Calculate gradient with default spacing
/// let (grad_y, grad_x) = gradient(a.view(), None).expect("Operation failed");
/// // Vertical gradient (y-direction)
/// assert_eq!(grad_y.shape(), &[2, 3]);
/// // Horizontal gradient (x-direction)
/// assert_eq!(grad_x.shape(), &[2, 3]);
/// ```
#[allow(dead_code)]
pub fn gradient<T>(array: ArrayView<T, Ix2>, spacing: Option<(T, T)>) -> GradientResult<T>
where
    T: Clone + num_traits::Float,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    if rows == 0 || cols == 0 {
        return Err("Input array must not be empty");
    }

    // Get spacing values (default to 1.0)
    let (dy, dx) = spacing.unwrap_or((T::one(), T::one()));

    // Create output arrays for gradients
    let mut grad_y = Array::<T, Ix2>::zeros((rows, cols));
    let mut grad_x = Array::<T, Ix2>::zeros((rows, cols));

    // Calculate gradient along y axis (rows)
    if rows == 1 {
        // Single row, gradient is zero
        // (already initialized with zeros)
    } else {
        // First row: forward difference
        for j in 0..cols {
            grad_y[[0, j]] = (array[[1, j]] - array[[0, j]]) / dy;
        }

        // Middle rows: central difference
        for i in 1..rows - 1 {
            for j in 0..cols {
                grad_y[[i, j]] = (array[[i + 1, j]] - array[[i.saturating_sub(1), j]]) / (dy + dy);
            }
        }

        // Last row: backward difference
        for j in 0..cols {
            grad_y[[rows - 1, j]] = (array[[rows - 1, j]] - array[[rows - 2, j]]) / dy;
        }
    }

    // Calculate gradient along x axis (columns)
    if cols == 1 {
        // Single column, gradient is zero
        // (already initialized with zeros)
    } else {
        for i in 0..rows {
            // First column: forward difference
            grad_x[[i, 0]] = (array[[i, 1]] - array[[i, 0]]) / dx;

            // Middle columns: central difference
            for j in 1..cols - 1 {
                grad_x[[i, j]] = (array[[i, j + 1]] - array[[i, j.saturating_sub(1)]]) / (dx + dx);
            }

            // Last column: backward difference
            grad_x[[i, cols - 1]] = (array[[i, cols - 1]] - array[[i, cols - 2]]) / dx;
        }
    }

    Ok((grad_y, grad_x))
}

#[cfg(test)]
mod tests {
    use super::*;
    use ::ndarray::array;
    use approx::assert_abs_diff_eq;

    #[test]
    fn test_flip_2d() {
        let a = array![[1, 2, 3], [4, 5, 6]];

        // Test flipping along axis 0 (rows)
        let flipped_rows = flip_2d(a.view(), true, false);
        assert_eq!(flipped_rows, array![[4, 5, 6], [1, 2, 3]]);

        // Test flipping along axis 1 (columns)
        let flipped_cols = flip_2d(a.view(), false, true);
        assert_eq!(flipped_cols, array![[3, 2, 1], [6, 5, 4]]);

        // Test flipping along both axes
        let flipped_both = flip_2d(a.view(), true, true);
        assert_eq!(flipped_both, array![[6, 5, 4], [3, 2, 1]]);
    }

    #[test]
    fn test_roll_2d() {
        let a = array![[1, 2, 3], [4, 5, 6]];

        // Test rolling along axis 0 (rows)
        let rolled_rows = roll_2d(a.view(), 1, 0);
        assert_eq!(rolled_rows, array![[4, 5, 6], [1, 2, 3]]);

        // Test rolling along axis 1 (columns)
        let rolled_cols = roll_2d(a.view(), 0, 1);
        assert_eq!(rolled_cols, array![[3, 1, 2], [6, 4, 5]]);

        // Test negative rolling
        let rolled_neg = roll_2d(a.view(), 0, -1);
        assert_eq!(rolled_neg, array![[2, 3, 1], [5, 6, 4]]);

        // Test rolling by zero (should return the original array)
        let rolled_zero = roll_2d(a.view(), 0, 0);
        assert_eq!(rolled_zero, a);
    }

    #[test]
    fn test_tile_2d() {
        let a = array![[1, 2], [3, 4]];

        // Test tiling along both axes
        let tiled = tile_2d(a.view(), 2, 3);
        assert_eq!(tiled.shape(), &[4, 6]);
        assert_eq!(
            tiled,
            array![
                [1, 2, 1, 2, 1, 2],
                [3, 4, 3, 4, 3, 4],
                [1, 2, 1, 2, 1, 2],
                [3, 4, 3, 4, 3, 4]
            ]
        );

        // Test tiling along axis 0 only
        let tiled_axis_0 = tile_2d(a.view(), 2, 1);
        assert_eq!(tiled_axis_0.shape(), &[4, 2]);
        assert_eq!(tiled_axis_0, array![[1, 2], [3, 4], [1, 2], [3, 4]]);

        // Test tiling a single element
        let single = array![[5]];
        let tiled_single = tile_2d(single.view(), 2, 2);
        assert_eq!(tiled_single.shape(), &[2, 2]);
        assert_eq!(tiled_single, array![[5, 5], [5, 5]]);
    }

    #[test]
    fn test_repeat_2d() {
        let a = array![[1, 2], [3, 4]];

        // Test repeating along both axes
        let repeated = repeat_2d(a.view(), 2, 3);
        assert_eq!(repeated.shape(), &[4, 6]);
        assert_eq!(
            repeated,
            array![
                [1, 1, 1, 2, 2, 2],
                [1, 1, 1, 2, 2, 2],
                [3, 3, 3, 4, 4, 4],
                [3, 3, 3, 4, 4, 4]
            ]
        );

        // Test repeating along axis 1 only
        let repeated_axis_1 = repeat_2d(a.view(), 1, 2);
        assert_eq!(repeated_axis_1.shape(), &[2, 4]);
        assert_eq!(repeated_axis_1, array![[1, 1, 2, 2], [3, 3, 4, 4]]);
    }

    #[test]
    fn test_swap_axes_2d() {
        let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];

        // Test swapping rows
        let swapped_rows = swap_axes_2d(a.view(), 0, 2, 0).expect("Operation failed");
        assert_eq!(swapped_rows, array![[7, 8, 9], [4, 5, 6], [1, 2, 3]]);

        // Test swapping columns
        let swapped_cols = swap_axes_2d(a.view(), 0, 2, 1).expect("Operation failed");
        assert_eq!(swapped_cols, array![[3, 2, 1], [6, 5, 4], [9, 8, 7]]);

        // Test swapping same indices (should return a clone of the original)
        let swapped_same = swap_axes_2d(a.view(), 1, 1, 0).expect("Operation failed");
        assert_eq!(swapped_same, a);

        // Test invalid axis
        assert!(swap_axes_2d(a.view(), 0, 1, 2).is_err());

        // Test out of bounds indices
        assert!(swap_axes_2d(a.view(), 0, 3, 0).is_err());
    }

    #[test]
    fn test_pad_2d() {
        let a = array![[1, 2], [3, 4]];

        // Test padding on all sides
        let padded_all = pad_2d(a.view(), ((1, 1), (1, 1)), 0);
        assert_eq!(padded_all.shape(), &[4, 4]);
        assert_eq!(
            padded_all,
            array![[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]
        );

        // Test uneven padding
        let padded_uneven = pad_2d(a.view(), ((2, 0), (0, 1)), 9);
        assert_eq!(padded_uneven.shape(), &[4, 3]);
        assert_eq!(
            padded_uneven,
            array![[9, 9, 9], [9, 9, 9], [1, 2, 9], [3, 4, 9]]
        );
    }

    #[test]
    fn test_concatenate_2d() {
        let a = array![[1, 2], [3, 4]];
        let b = array![[5, 6], [7, 8]];

        // Test concatenating along axis 0 (vertically)
        let vertical = concatenate_2d(&[a.view(), b.view()], 0).expect("Operation failed");
        assert_eq!(vertical.shape(), &[4, 2]);
        assert_eq!(vertical, array![[1, 2], [3, 4], [5, 6], [7, 8]]);

        // Test concatenating along axis 1 (horizontally)
        let horizontal = concatenate_2d(&[a.view(), b.view()], 1).expect("Operation failed");
        assert_eq!(horizontal.shape(), &[2, 4]);
        assert_eq!(horizontal, array![[1, 2, 5, 6], [3, 4, 7, 8]]);

        // Test concatenating with incompatible shapes
        let c = array![[9, 10, 11]];
        assert!(concatenate_2d(&[a.view(), c.view()], 0).is_err());

        // Test concatenating empty array list
        let empty: [ArrayView<i32, Ix2>; 0] = [];
        assert!(concatenate_2d(&empty, 0).is_err());

        // Test invalid axis
        assert!(concatenate_2d(&[a.view(), b.view()], 2).is_err());
    }

    #[test]
    fn test_vstack_1d() {
        let a = array![1, 2, 3];
        let b = array![4, 5, 6];
        let c = array![7, 8, 9];

        // Test stacking multiple arrays
        let stacked = vstack_1d(&[a.view(), b.view(), c.view()]).expect("Operation failed");
        assert_eq!(stacked.shape(), &[3, 3]);
        assert_eq!(stacked, array![[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

        // Test stacking empty list
        let empty: [ArrayView<i32, Ix1>; 0] = [];
        assert!(vstack_1d(&empty).is_err());

        // Test inconsistent lengths
        let d = array![10, 11];
        assert!(vstack_1d(&[a.view(), d.view()]).is_err());
    }

    #[test]
    fn test_hstack_1d() {
        let a = array![1, 2, 3];
        let b = array![4, 5, 6];

        // Test stacking multiple arrays
        let stacked = hstack_1d(&[a.view(), b.view()]).expect("Operation failed");
        assert_eq!(stacked.shape(), &[3, 2]);
        assert_eq!(stacked, array![[1, 4], [2, 5], [3, 6]]);

        // Test stacking empty list
        let empty: [ArrayView<i32, Ix1>; 0] = [];
        assert!(hstack_1d(&empty).is_err());

        // Test inconsistent lengths
        let c = array![7, 8];
        assert!(hstack_1d(&[a.view(), c.view()]).is_err());
    }

    #[test]
    fn test_squeeze_2d() {
        let a = array![[1, 2, 3]]; // 1x3 array
        let b = array![[1], [2], [3]]; // 3x1 array

        // Test squeezing axis 0
        let squeezed_a = squeeze_2d(a.view(), 0).expect("Operation failed");
        assert_eq!(squeezed_a.shape(), &[3]);
        assert_eq!(squeezed_a, array![1, 2, 3]);

        // Test squeezing axis 1
        let squeezed_b = squeeze_2d(b.view(), 1).expect("Operation failed");
        assert_eq!(squeezed_b.shape(), &[3]);
        assert_eq!(squeezed_b, array![1, 2, 3]);

        // Test squeezing on an axis with size > 1 (should fail)
        let c = array![[1, 2], [3, 4]]; // 2x2 array
        assert!(squeeze_2d(c.view(), 0).is_err());
        assert!(squeeze_2d(c.view(), 1).is_err());

        // Test invalid axis
        assert!(squeeze_2d(a.view(), 2).is_err());
    }

    #[test]
    fn test_meshgrid() {
        let x = array![1, 2, 3];
        let y = array![4, 5];

        let (x_grid, y_grid) = meshgrid(x.view(), y.view()).expect("Operation failed");
        assert_eq!(x_grid.shape(), &[2, 3]);
        assert_eq!(y_grid.shape(), &[2, 3]);
        assert_eq!(x_grid, array![[1, 2, 3], [1, 2, 3]]);
        assert_eq!(y_grid, array![[4, 4, 4], [5, 5, 5]]);

        // Test empty arrays
        let empty = array![];
        assert!(meshgrid(x.view(), empty.view()).is_err());
        assert!(meshgrid(empty.view(), y.view()).is_err());
    }

    #[test]
    fn test_unique() {
        let a = array![3, 1, 2, 2, 3, 4, 1];
        let result = unique(a.view()).expect("Operation failed");
        assert_eq!(result, array![1, 2, 3, 4]);

        // Test empty array
        let empty: Array<i32, Ix1> = array![];
        assert!(unique(empty.view()).is_err());
    }

    #[test]
    fn test_argmin() {
        let a = array![[5, 2, 3], [4, 1, 6]];

        // Test along axis 0
        let result = argmin(a.view(), Some(0)).expect("Operation failed");
        assert_eq!(result, array![1, 1, 0]);

        // Test along axis 1
        let result = argmin(a.view(), Some(1)).expect("Operation failed");
        assert_eq!(result, array![1, 1]);

        // Test flattened array
        let result = argmin(a.view(), None).expect("Operation failed");
        assert_eq!(result[0], 4); // Index of 1 in the flattened array (row 1, col 1)

        // Test invalid axis
        assert!(argmin(a.view(), Some(2)).is_err());

        // Test empty array
        let empty: Array<i32, Ix2> = Array::zeros((0, 0));
        assert!(argmin(empty.view(), Some(0)).is_err());
    }

    #[test]
    fn test_argmax() {
        let a = array![[5, 2, 3], [4, 1, 6]];

        // Test along axis 0
        let result = argmax(a.view(), Some(0)).expect("Operation failed");
        assert_eq!(result, array![0, 0, 1]);

        // Test along axis 1
        let result = argmax(a.view(), Some(1)).expect("Operation failed");
        assert_eq!(result, array![0, 2]);

        // Test flattened array
        let result = argmax(a.view(), None).expect("Operation failed");
        assert_eq!(result[0], 5); // Index of 6 in the flattened array (row 1, col 2)

        // Test invalid axis
        assert!(argmax(a.view(), Some(2)).is_err());

        // Test empty array
        let empty: Array<i32, Ix2> = Array::zeros((0, 0));
        assert!(argmax(empty.view(), Some(0)).is_err());
    }

    #[test]
    fn test_gradient() {
        let a = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];

        // Calculate gradient with default spacing
        let (grad_y, grad_x) = gradient(a.view(), None).expect("Operation failed");

        // Verify shapes
        assert_eq!(grad_y.shape(), &[2, 3]);
        assert_eq!(grad_x.shape(), &[2, 3]);

        // Check gradient values
        // Vertical gradient (y-direction)
        assert_abs_diff_eq!(grad_y[[0, 0]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[0, 1]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[0, 2]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[1, 0]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[1, 1]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[1, 2]], 3.0, epsilon = 1e-10);

        // Horizontal gradient (x-direction)
        assert_abs_diff_eq!(grad_x[[0, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[0, 1]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[0, 2]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[1, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[1, 1]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[1, 2]], 1.0, epsilon = 1e-10);

        // Test with custom spacing
        let (grad_y, grad_x) = gradient(a.view(), Some((2.0, 0.5))).expect("Operation failed");

        // Vertical gradient (y-direction) with spacing = 2.0
        assert_abs_diff_eq!(grad_y[[0, 0]], 1.5, epsilon = 1e-10); // 3.0 / 2.0
        assert_abs_diff_eq!(grad_y[[0, 1]], 1.5, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_y[[0, 2]], 1.5, epsilon = 1e-10);

        // Horizontal gradient (x-direction) with spacing = 0.5
        assert_abs_diff_eq!(grad_x[[0, 0]], 2.0, epsilon = 1e-10); // 1.0 / 0.5
        assert_abs_diff_eq!(grad_x[[0, 1]], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(grad_x[[0, 2]], 2.0, epsilon = 1e-10);

        // Test empty array
        let empty: Array<f32, Ix2> = Array::zeros((0, 0));
        assert!(gradient(empty.view(), None).is_err());
    }
}