numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
//! Advanced indexing operations for Arrays
//!
//! This module provides advanced indexing functionality similar to NumPy's
//! advanced indexing capabilities, including compress, extract, place, put,
//! and other sophisticated indexing operations.

use crate::array::Array;
use crate::error::{NumRs2Error, Result};
use num_traits::Zero;

/// Return selected slices of an array along given axis
///
/// # Arguments
/// * `array` - Input array
/// * `condition` - 1-D array of booleans corresponding to indices to select
/// * `axis` - Axis along which to take slices. If None, work on flattened array
///
/// # Returns
/// * `Result<Array<T>>` - Array with selected slices
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::compress;
///
/// let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
/// let condition = Array::from_vec(vec![true, false, true, false, true]);
/// let compressed = compress(&arr, &condition, None).expect("operation should succeed");
/// // Returns [1, 3, 5]
///
/// let arr2d = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
/// let cond = Array::from_vec(vec![true, false, true]);
/// let compressed = compress(&arr2d, &cond, Some(1)).expect("operation should succeed");
/// // Returns [[1, 3], [4, 6]] (columns 0 and 2)
/// ```
pub fn compress<T: Clone + Zero>(
    array: &Array<T>,
    condition: &Array<bool>,
    axis: Option<usize>,
) -> Result<Array<T>> {
    match axis {
        None => {
            // Work on flattened array
            let flat = array.to_vec();
            let cond_flat = condition.to_vec();

            if flat.len() != cond_flat.len() {
                return Err(NumRs2Error::ShapeMismatch {
                    expected: vec![flat.len()],
                    actual: vec![cond_flat.len()],
                });
            }

            let compressed: Vec<T> = flat
                .into_iter()
                .zip(cond_flat)
                .filter_map(|(val, cond)| if cond { Some(val) } else { None })
                .collect();

            Ok(Array::from_vec(compressed))
        }
        Some(ax) => {
            let shape = array.shape();
            if ax >= shape.len() {
                return Err(NumRs2Error::DimensionMismatch(format!(
                    "axis {} is out of bounds for array of dimension {}",
                    ax,
                    shape.len()
                )));
            }

            let cond_vec = condition.to_vec();
            if cond_vec.len() != shape[ax] {
                return Err(NumRs2Error::ShapeMismatch {
                    expected: vec![shape[ax]],
                    actual: vec![cond_vec.len()],
                });
            }

            // Determine which indices to keep
            let indices: Vec<usize> = cond_vec
                .into_iter()
                .enumerate()
                .filter_map(|(i, cond)| if cond { Some(i) } else { None })
                .collect();

            // Calculate new shape
            let mut new_shape = shape.clone();
            new_shape[ax] = indices.len();

            if indices.is_empty() {
                return Ok(Array::zeros(&new_shape));
            }

            // Extract selected slices
            let mut result_data = Vec::with_capacity(new_shape.iter().product());

            // Helper to iterate through all indices
            let mut current_indices = vec![0; shape.len()];
            let total_elements: usize = shape.iter().product();

            for _ in 0..total_elements {
                // Check if current index along axis is in our selection
                if indices.contains(&current_indices[ax]) {
                    let value = array.get(&current_indices)?;
                    result_data.push(value);
                }

                // Increment indices
                let mut carry = true;
                for dim in (0..shape.len()).rev() {
                    if carry {
                        current_indices[dim] += 1;
                        carry = current_indices[dim] >= shape[dim];
                        if carry {
                            current_indices[dim] = 0;
                        }
                    }
                }
            }

            Ok(Array::from_vec(result_data).reshape(&new_shape))
        }
    }
}

/// Return the elements of an array that satisfy some condition
///
/// This is equivalent to `array[condition]` in NumPy where condition is a boolean array.
///
/// # Arguments
/// * `array` - Input array
/// * `condition` - Boolean array with same shape as `array`
///
/// # Returns
/// * `Result<Array<T>>` - 1-D array with elements where condition is True
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::extract;
///
/// let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
/// let condition = Array::from_vec(vec![true, false, true, false, true, false]).reshape(&[2, 3]);
/// let extracted = extract(&arr, &condition).expect("operation should succeed");
/// // Returns [1, 3, 5]
/// ```
pub fn extract<T: Clone>(array: &Array<T>, condition: &Array<bool>) -> Result<Array<T>> {
    if array.shape() != condition.shape() {
        return Err(NumRs2Error::ShapeMismatch {
            expected: array.shape(),
            actual: condition.shape(),
        });
    }

    let data = array.to_vec();
    let cond_data = condition.to_vec();

    let extracted: Vec<T> = data
        .into_iter()
        .zip(cond_data)
        .filter_map(|(val, cond)| if cond { Some(val) } else { None })
        .collect();

    Ok(Array::from_vec(extracted))
}

/// Place values into array at specified indices
///
/// # Arguments
/// * `array` - Array to modify (modified in-place)
/// * `mask` - Boolean array indicating where to place values
/// * `values` - Values to place (will be repeated if necessary)
///
/// # Returns
/// * `Result<()>` - Success or error
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::place;
///
/// let mut arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
/// let mask = Array::from_vec(vec![false, true, false, true, false]);
/// place(&mut arr, &mask, &[10, 20]).expect("operation should succeed");
/// // arr is now [1, 10, 3, 20, 5]
/// ```
pub fn place<T: Clone>(array: &mut Array<T>, mask: &Array<bool>, values: &[T]) -> Result<()> {
    if array.shape() != mask.shape() {
        return Err(NumRs2Error::ShapeMismatch {
            expected: array.shape(),
            actual: mask.shape(),
        });
    }

    if values.is_empty() {
        return Err(NumRs2Error::ValueError(
            "values array cannot be empty".to_string(),
        ));
    }

    let mask_data = mask.to_vec();
    let num_true = mask_data.iter().filter(|&&x| x).count();

    if num_true == 0 {
        return Ok(()); // Nothing to place
    }

    // Get mutable slice
    let array_data = array
        .array_mut()
        .as_slice_mut()
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to get mutable slice".into()))?;

    let mut value_idx = 0;
    for (i, &is_true) in mask_data.iter().enumerate() {
        if is_true {
            array_data[i] = values[value_idx % values.len()].clone();
            value_idx += 1;
        }
    }

    Ok(())
}

/// Replaces specified elements of array with given values
///
/// # Arguments
/// * `array` - Array to modify (modified in-place)
/// * `indices` - 1-D array of indices
/// * `values` - Values to put at those indices
///
/// # Returns
/// * `Result<()>` - Success or error
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::put;
///
/// let mut arr = Array::from_vec(vec![0, 0, 0, 0, 0]);
/// let indices = Array::from_vec(vec![0, 2, 4]);
/// put(&mut arr, &indices, &[10, 20, 30]).expect("operation should succeed");
/// // arr is now [10, 0, 20, 0, 30]
/// ```
pub fn put<T: Clone>(array: &mut Array<T>, indices: &Array<usize>, values: &[T]) -> Result<()> {
    if values.is_empty() {
        return Err(NumRs2Error::ValueError(
            "values array cannot be empty".to_string(),
        ));
    }

    let indices_vec = indices.to_vec();
    let array_len = array.size();

    // Validate indices
    for &idx in &indices_vec {
        if idx >= array_len {
            return Err(NumRs2Error::IndexOutOfBounds(format!(
                "index {} is out of bounds for array of size {}",
                idx, array_len
            )));
        }
    }

    // Get mutable slice
    let array_data = array
        .array_mut()
        .as_slice_mut()
        .ok_or_else(|| NumRs2Error::InvalidOperation("Failed to get mutable slice".into()))?;

    for (i, &idx) in indices_vec.iter().enumerate() {
        array_data[idx] = values[i % values.len()].clone();
    }

    Ok(())
}

/// Put values into array using a mask
///
/// # Arguments
/// * `array` - Array to modify (modified in-place)
/// * `mask` - Boolean mask array  
/// * `values` - Array of values to put where mask is True
///
/// # Returns
/// * `Result<()>` - Success or error
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::putmask;
///
/// let mut arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
/// let mask = Array::from_vec(vec![false, true, false, true, false]);
/// let values = Array::from_vec(vec![10, 20]);
/// putmask(&mut arr, &mask, &values).expect("operation should succeed");
/// // arr is now [1, 10, 3, 20, 5]
/// ```
pub fn putmask<T: Clone>(
    array: &mut Array<T>,
    mask: &Array<bool>,
    values: &Array<T>,
) -> Result<()> {
    place(array, mask, &values.to_vec())
}

/// Take values from array along an axis using indices
///
/// # Arguments
/// * `array` - Input array
/// * `indices` - Array of indices to take
/// * `axis` - Axis along which to take values
///
/// # Returns
/// * `Result<Array<T>>` - Array with values taken along the specified axis
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::take_along_axis;
///
/// let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
/// let indices = Array::from_vec(vec![0, 2, 1, 0]).reshape(&[2, 2]);
/// let result = take_along_axis(&arr, &indices, 1).expect("operation should succeed");
/// // For row 0: takes elements at indices [0, 2] -> [1, 3]
/// // For row 1: takes elements at indices [1, 0] -> [5, 4]
/// // Result is [[1, 3], [5, 4]]
/// ```
pub fn take_along_axis<T: Clone + Zero>(
    array: &Array<T>,
    indices: &Array<usize>,
    axis: usize,
) -> Result<Array<T>> {
    let arr_shape = array.shape();
    let ind_shape = indices.shape();

    if axis >= arr_shape.len() {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "axis {} is out of bounds for array of dimension {}",
            axis,
            arr_shape.len()
        )));
    }

    // Check that shapes match except along the specified axis
    if arr_shape.len() != ind_shape.len() {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "array and indices must have same number of dimensions, got {} and {}",
            arr_shape.len(),
            ind_shape.len()
        )));
    }

    for (i, (&arr_dim, &ind_dim)) in arr_shape.iter().zip(ind_shape.iter()).enumerate() {
        if i != axis && arr_dim != ind_dim {
            return Err(NumRs2Error::ShapeMismatch {
                expected: arr_shape.clone(),
                actual: ind_shape.clone(),
            });
        }
    }

    // Create result array with same shape as indices
    let mut result_data = Vec::with_capacity(indices.size());

    // Iterate through all positions in indices array
    let mut current_pos = vec![0; ind_shape.len()];
    let total_elements = indices.size();

    for _ in 0..total_elements {
        // Get the index value at current position
        let idx = indices.get(&current_pos)?;

        // Check bounds
        if idx >= arr_shape[axis] {
            return Err(NumRs2Error::IndexOutOfBounds(format!(
                "index {} is out of bounds for axis {} with size {}",
                idx, axis, arr_shape[axis]
            )));
        }

        // Build position in source array
        let mut source_pos = current_pos.clone();
        source_pos[axis] = idx;

        // Get value and add to result
        let value = array.get(&source_pos)?;
        result_data.push(value);

        // Increment position
        let mut carry = true;
        for dim in (0..ind_shape.len()).rev() {
            if carry {
                current_pos[dim] += 1;
                carry = current_pos[dim] >= ind_shape[dim];
                if carry {
                    current_pos[dim] = 0;
                }
            }
        }
    }

    Ok(Array::from_vec(result_data).reshape(&ind_shape))
}

/// Apply a function to 1-D slices along the given axis
///
/// # Arguments
/// * `func` - Function to apply to each 1-D slice
/// * `array` - Input array
/// * `axis` - Axis along which array is sliced
///
/// # Returns
/// * `Result<Array<U>>` - Array with function applied along axis
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::apply_along_axis;
///
/// // Sum along axis
/// let arr = Array::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).reshape(&[2, 3]);
/// let result = apply_along_axis(
///     |slice: &Array<f64>| -> f64 { slice.sum() },
///     &arr,
///     1
/// ).expect("operation should succeed");
/// // Sums each row: [6.0, 15.0]
/// ```
pub fn apply_along_axis<T, U, F>(func: F, array: &Array<T>, axis: usize) -> Result<Array<U>>
where
    T: Clone + Zero,
    U: Clone + Zero,
    F: Fn(&Array<T>) -> U,
{
    let shape = array.shape();

    if axis >= shape.len() {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "axis {} is out of bounds for array of dimension {}",
            axis,
            shape.len()
        )));
    }

    // Calculate output shape (remove the axis dimension)
    let mut out_shape = shape.clone();
    out_shape.remove(axis);

    if out_shape.is_empty() {
        // If only one dimension, return scalar as 1-element array
        let result = func(array);
        return Ok(Array::from_vec(vec![result]));
    }

    let mut result_data = Vec::new();

    // Number of slices to process
    let n_slices: usize = out_shape.iter().product();

    for slice_idx in 0..n_slices {
        // Convert linear index to multi-dimensional position
        let mut slice_pos = vec![0; out_shape.len()];
        let mut temp = slice_idx;
        for i in (0..out_shape.len()).rev() {
            slice_pos[i] = temp % out_shape[i];
            temp /= out_shape[i];
        }

        // Extract 1-D slice along the axis
        let mut slice_data = Vec::with_capacity(shape[axis]);

        for i in 0..shape[axis] {
            // Build full position in original array
            let mut full_pos = Vec::with_capacity(shape.len());
            let mut slice_dim = 0;

            for dim in 0..shape.len() {
                if dim == axis {
                    full_pos.push(i);
                } else {
                    full_pos.push(slice_pos[slice_dim]);
                    slice_dim += 1;
                }
            }

            slice_data.push(array.get(&full_pos)?);
        }

        // Apply function to slice
        let slice_array = Array::from_vec(slice_data);
        let result = func(&slice_array);
        result_data.push(result);
    }

    Ok(Array::from_vec(result_data).reshape(&out_shape))
}

/// Apply a function over multiple axes
///
/// # Arguments
/// * `func` - Function that takes an array and returns a scalar
/// * `array` - Input array
/// * `axes` - Axes over which to apply the function
///
/// # Returns
/// * `Result<Array<T>>` - Result array with specified axes removed
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::apply_over_axes;
///
/// // Sum over multiple axes
/// let arr = Array::from_vec(vec![
///     1.0, 2.0, 3.0, 4.0,
///     5.0, 6.0, 7.0, 8.0
/// ]);
/// let arr = arr.reshape(&[2, 2, 2]);
///
/// let result = apply_over_axes(
///     |a: &Array<f64>| -> Result<Array<f64>> { a.sum_axis(0) },
///     &arr,
///     &[1]
/// ).expect("operation should succeed");
/// // Sums over axis 1, reducing dimension by 1
/// ```
pub fn apply_over_axes<T, F>(func: F, array: &Array<T>, axes: &[usize]) -> Result<Array<T>>
where
    T: Clone + Zero,
    F: Fn(&Array<T>) -> Result<Array<T>>,
{
    let mut result = array.clone();

    // Sort axes in descending order to handle removal correctly
    let mut sorted_axes = axes.to_vec();
    sorted_axes.sort_by(|a, b| b.cmp(a));

    for &axis in &sorted_axes {
        if axis >= result.ndim() {
            return Err(NumRs2Error::DimensionMismatch(format!(
                "axis {} is out of bounds for array of dimension {}",
                axis,
                result.ndim()
            )));
        }

        // Apply function along this axis
        let temp = func(&result)?;

        // The function should reduce the dimension along the axis
        if temp.ndim() != result.ndim() - 1 {
            return Err(NumRs2Error::InvalidOperation(
                "Function must reduce dimension by 1".to_string(),
            ));
        }

        result = temp;
    }

    Ok(result)
}

/// Take elements from array using integer array indices (fancy indexing)
///
/// This implements NumPy-style fancy indexing where an array of integers
/// is used to select elements from the input array. The result has the
/// same shape as the indices array.
///
/// # Arguments
/// * `array` - Input array
/// * `indices` - Integer array of indices to take
/// * `axis` - Optional axis along which to take. If None, array is flattened
///
/// # Returns
/// * `Result<Array<T>>` - Array with selected elements
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::take;
///
/// // 1-D fancy indexing
/// let arr = Array::from_vec(vec![10, 20, 30, 40, 50]);
/// let indices = Array::from_vec(vec![0, 2, 4, 1]);
/// let result = take(&arr, &indices, None).expect("operation should succeed");
/// // Returns [10, 30, 50, 20]
///
/// // 2-D fancy indexing along axis
/// let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
/// let indices = Array::from_vec(vec![2, 0, 1]);
/// let result = take(&arr, &indices, Some(1)).expect("operation should succeed");
/// // Takes columns [2, 0, 1] from each row
/// ```
pub fn take<T: Clone + Zero>(
    array: &Array<T>,
    indices: &Array<usize>,
    axis: Option<usize>,
) -> Result<Array<T>> {
    match axis {
        None => {
            // Flatten array and take elements
            let flat = array.to_vec();
            let idx_vec = indices.to_vec();

            // Validate indices
            for &idx in &idx_vec {
                if idx >= flat.len() {
                    return Err(NumRs2Error::IndexOutOfBounds(format!(
                        "index {} is out of bounds for flattened array of size {}",
                        idx,
                        flat.len()
                    )));
                }
            }

            // Take elements
            let result: Vec<T> = idx_vec.iter().map(|&idx| flat[idx].clone()).collect();

            // Result has same shape as indices
            Ok(Array::from_vec(result).reshape(&indices.shape()))
        }
        Some(ax) => {
            let shape = array.shape();

            if ax >= shape.len() {
                return Err(NumRs2Error::DimensionMismatch(format!(
                    "axis {} is out of bounds for array of dimension {}",
                    ax,
                    shape.len()
                )));
            }

            let idx_vec = indices.to_vec();

            // Validate indices
            for &idx in &idx_vec {
                if idx >= shape[ax] {
                    return Err(NumRs2Error::IndexOutOfBounds(format!(
                        "index {} is out of bounds for axis {} with size {}",
                        idx, ax, shape[ax]
                    )));
                }
            }

            // Calculate result shape
            let mut result_shape = shape.clone();
            result_shape[ax] = idx_vec.len();

            let mut result_data = Vec::with_capacity(result_shape.iter().product());

            // Iterate through all positions
            let mut current_pos = vec![0; shape.len()];
            let total_out: usize = result_shape.iter().product();

            for _ in 0..total_out {
                // Map position in result to position in source
                let mut source_pos = current_pos.clone();
                source_pos[ax] = idx_vec[current_pos[ax]];

                let value = array.get(&source_pos)?;
                result_data.push(value);

                // Increment position
                let mut carry = true;
                for dim in (0..result_shape.len()).rev() {
                    if carry {
                        current_pos[dim] += 1;
                        carry = current_pos[dim] >= result_shape[dim];
                        if carry {
                            current_pos[dim] = 0;
                        }
                    }
                }
            }

            Ok(Array::from_vec(result_data).reshape(&result_shape))
        }
    }
}

/// Multi-dimensional fancy indexing using coordinate arrays
///
/// Select elements at specific coordinates specified by arrays of indices.
/// This is equivalent to `array[indices[0], indices[1], ...]` in NumPy.
///
/// # Arguments
/// * `array` - Input array
/// * `indices` - Slice of index arrays, one per dimension
///
/// # Returns
/// * `Result<Array<T>>` - 1-D array with selected elements
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::fancy_index;
///
/// let arr = Array::from_vec(vec![
///     1, 2, 3,
///     4, 5, 6,
///     7, 8, 9
/// ]).reshape(&[3, 3]);
///
/// // Select elements at (0,0), (1,1), (2,2) - the diagonal
/// let row_idx = Array::from_vec(vec![0, 1, 2]);
/// let col_idx = Array::from_vec(vec![0, 1, 2]);
/// let result = fancy_index(&arr, &[row_idx, col_idx]).expect("operation should succeed");
/// // Returns [1, 5, 9]
///
/// // Select elements at (0,2), (2,0)
/// let row_idx = Array::from_vec(vec![0, 2]);
/// let col_idx = Array::from_vec(vec![2, 0]);
/// let result = fancy_index(&arr, &[row_idx, col_idx]).expect("operation should succeed");
/// // Returns [3, 7]
/// ```
pub fn fancy_index<T: Clone + Zero>(
    array: &Array<T>,
    indices: &[Array<usize>],
) -> Result<Array<T>> {
    let shape = array.shape();

    if indices.is_empty() {
        return Err(NumRs2Error::ValueError(
            "indices array cannot be empty".to_string(),
        ));
    }

    if indices.len() != shape.len() {
        return Err(NumRs2Error::DimensionMismatch(format!(
            "number of index arrays ({}) must match array dimensions ({})",
            indices.len(),
            shape.len()
        )));
    }

    // All index arrays must have the same shape
    let idx_shape = indices[0].shape();
    for idx_arr in &indices[1..] {
        if idx_arr.shape() != idx_shape {
            return Err(NumRs2Error::ShapeMismatch {
                expected: idx_shape.clone(),
                actual: idx_arr.shape(),
            });
        }
    }

    let num_elements = indices[0].size();
    let mut result_data = Vec::with_capacity(num_elements);

    // Convert all index arrays to vectors
    let idx_vecs: Vec<Vec<usize>> = indices.iter().map(|arr| arr.to_vec()).collect();

    // For each element position
    for i in 0..num_elements {
        // Build coordinate from index arrays
        let mut coord = Vec::with_capacity(shape.len());
        for (dim, idx_vec) in idx_vecs.iter().enumerate() {
            let idx = idx_vec[i];

            // Validate index
            if idx >= shape[dim] {
                return Err(NumRs2Error::IndexOutOfBounds(format!(
                    "index {} is out of bounds for dimension {} with size {}",
                    idx, dim, shape[dim]
                )));
            }

            coord.push(idx);
        }

        // Get element at coordinate
        let value = array.get(&coord)?;
        result_data.push(value);
    }

    // Result has same shape as the index arrays
    Ok(Array::from_vec(result_data).reshape(&idx_shape))
}

/// Boolean indexing convenience method
///
/// Extract elements from array using a boolean mask. This is a convenience
/// wrapper around `extract()` that returns a flattened array.
///
/// # Arguments
/// * `array` - Input array
/// * `mask` - Boolean mask with same shape as array
///
/// # Returns
/// * `Result<Array<T>>` - 1-D array with elements where mask is true
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::boolean_index;
///
/// let arr = Array::from_vec(vec![10, 20, 30, 40, 50]);
/// let mask = Array::from_vec(vec![true, false, true, false, true]);
/// let result = boolean_index(&arr, &mask).expect("operation should succeed");
/// // Returns [10, 30, 50]
///
/// // Works with comparisons
/// let arr = Array::from_vec(vec![1, 5, 3, 8, 2]);
/// let mask = arr.map(|x| x > 3);  // [false, true, false, true, false]
/// let result = boolean_index(&arr, &mask).expect("operation should succeed");
/// // Returns [5, 8]
/// ```
pub fn boolean_index<T: Clone>(array: &Array<T>, mask: &Array<bool>) -> Result<Array<T>> {
    extract(array, mask)
}

/// Choose elements from arrays based on conditions
///
/// Given a list of conditions and a list of choices, return an array drawn
/// from elements in choices, based on conditions. This is similar to NumPy's
/// `select()` function.
///
/// # Arguments
/// * `conditions` - List of boolean arrays. Each must have same shape
/// * `choices` - List of arrays to choose from. Each must match conditions shape
/// * `default` - Default value when no condition is met
///
/// # Returns
/// * `Result<Array<T>>` - Array with elements chosen based on conditions
///
/// # Examples
/// ```
/// use numrs2::prelude::*;
/// use numrs2::array_ops::advanced_indexing::select;
///
/// let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
///
/// // Condition 1: x < 3 -> return x * 10
/// let cond1 = arr.map(|x| x < 3);
/// let choice1 = arr.map(|x| x * 10);
///
/// // Condition 2: x >= 3 -> return x * 100
/// let cond2 = arr.map(|x| x >= 3);
/// let choice2 = arr.map(|x| x * 100);
///
/// let result = select(&[cond1, cond2], &[choice1, choice2], 0).expect("operation should succeed");
/// // Returns [10, 20, 300, 400, 500]
/// ```
pub fn select<T: Clone>(
    conditions: &[Array<bool>],
    choices: &[Array<T>],
    default: T,
) -> Result<Array<T>> {
    if conditions.is_empty() {
        return Err(NumRs2Error::ValueError(
            "conditions array cannot be empty".to_string(),
        ));
    }

    if conditions.len() != choices.len() {
        return Err(NumRs2Error::ValueError(format!(
            "number of conditions ({}) must match number of choices ({})",
            conditions.len(),
            choices.len()
        )));
    }

    // All conditions and choices must have same shape
    let shape = conditions[0].shape();
    for cond in &conditions[1..] {
        if cond.shape() != shape {
            return Err(NumRs2Error::ShapeMismatch {
                expected: shape.clone(),
                actual: cond.shape(),
            });
        }
    }

    for choice in choices {
        if choice.shape() != shape {
            return Err(NumRs2Error::ShapeMismatch {
                expected: shape.clone(),
                actual: choice.shape(),
            });
        }
    }

    // Convert to vectors for easier access
    let cond_vecs: Vec<Vec<bool>> = conditions.iter().map(|c| c.to_vec()).collect();
    let choice_vecs: Vec<Vec<T>> = choices.iter().map(|c| c.to_vec()).collect();

    let num_elements = conditions[0].size();
    let mut result_data = Vec::with_capacity(num_elements);

    // For each element position
    for i in 0..num_elements {
        let mut selected = false;

        // Check conditions in order
        for (cond_vec, choice_vec) in cond_vecs.iter().zip(choice_vecs.iter()) {
            if cond_vec[i] {
                result_data.push(choice_vec[i].clone());
                selected = true;
                break;
            }
        }

        // If no condition matched, use default
        if !selected {
            result_data.push(default.clone());
        }
    }

    Ok(Array::from_vec(result_data).reshape(&shape))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_take_1d() {
        let arr = Array::from_vec(vec![10, 20, 30, 40, 50]);
        let indices = Array::from_vec(vec![0, 2, 4, 1]);

        let result = take(&arr, &indices, None).expect("operation should succeed");

        assert_eq!(result.shape(), &[4]);
        assert_eq!(result.to_vec(), vec![10, 30, 50, 20]);
    }

    #[test]
    fn test_take_2d_no_axis() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
        let indices = Array::from_vec(vec![0, 3, 5]);

        let result = take(&arr, &indices, None).expect("operation should succeed");

        assert_eq!(result.shape(), &[3]);
        assert_eq!(result.to_vec(), vec![1, 4, 6]);
    }

    #[test]
    fn test_take_along_axis() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
        let indices = Array::from_vec(vec![2, 0, 1]);

        let result = take(&arr, &indices, Some(1)).expect("operation should succeed");

        assert_eq!(result.shape(), &[2, 3]);
        // Row 0: [1, 2, 3] -> indices [2, 0, 1] -> [3, 1, 2]
        // Row 1: [4, 5, 6] -> indices [2, 0, 1] -> [6, 4, 5]
        assert_eq!(result.to_vec(), vec![3, 1, 2, 6, 4, 5]);
    }

    #[test]
    fn test_take_out_of_bounds() {
        let arr = Array::from_vec(vec![1, 2, 3]);
        let indices = Array::from_vec(vec![0, 5]); // 5 is out of bounds

        let result = take(&arr, &indices, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_fancy_index_diagonal() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(&[3, 3]);

        let row_idx = Array::from_vec(vec![0, 1, 2]);
        let col_idx = Array::from_vec(vec![0, 1, 2]);

        let result = fancy_index(&arr, &[row_idx, col_idx]).expect("operation should succeed");

        assert_eq!(result.shape(), &[3]);
        assert_eq!(result.to_vec(), vec![1, 5, 9]);
    }

    #[test]
    fn test_fancy_index_arbitrary_coords() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(&[3, 3]);

        let row_idx = Array::from_vec(vec![0, 2, 1]);
        let col_idx = Array::from_vec(vec![2, 0, 1]);

        let result = fancy_index(&arr, &[row_idx, col_idx]).expect("operation should succeed");

        assert_eq!(result.shape(), &[3]);
        // (0,2) -> 3, (2,0) -> 7, (1,1) -> 5
        assert_eq!(result.to_vec(), vec![3, 7, 5]);
    }

    #[test]
    fn test_fancy_index_2d_indices() {
        let arr = Array::from_vec(vec![10, 20, 30, 40, 50, 60]).reshape(&[2, 3]);

        let row_idx = Array::from_vec(vec![0, 1, 0, 1]).reshape(&[2, 2]);
        let col_idx = Array::from_vec(vec![0, 1, 2, 2]).reshape(&[2, 2]);

        let result = fancy_index(&arr, &[row_idx, col_idx]).expect("operation should succeed");

        assert_eq!(result.shape(), &[2, 2]);
        // (0,0)->10, (1,1)->50, (0,2)->30, (1,2)->60
        assert_eq!(result.to_vec(), vec![10, 50, 30, 60]);
    }

    #[test]
    fn test_fancy_index_mismatched_shapes() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);

        let row_idx = Array::from_vec(vec![0, 1]);
        let col_idx = Array::from_vec(vec![0, 1, 2]); // Different shape

        let result = fancy_index(&arr, &[row_idx, col_idx]);
        assert!(result.is_err());
    }

    #[test]
    fn test_fancy_index_out_of_bounds() {
        let arr = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);

        let row_idx = Array::from_vec(vec![0, 3]); // 3 is out of bounds
        let col_idx = Array::from_vec(vec![0, 0]);

        let result = fancy_index(&arr, &[row_idx, col_idx]);
        assert!(result.is_err());
    }

    #[test]
    fn test_boolean_index_simple() {
        let arr = Array::from_vec(vec![10, 20, 30, 40, 50]);
        let mask = Array::from_vec(vec![true, false, true, false, true]);

        let result = boolean_index(&arr, &mask).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![10, 30, 50]);
    }

    #[test]
    fn test_boolean_index_with_comparison() {
        let arr = Array::from_vec(vec![1, 5, 3, 8, 2]);
        let mask = arr.map(|x| x > 3);

        let result = boolean_index(&arr, &mask).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![5, 8]);
    }

    #[test]
    fn test_boolean_index_2d() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5, 6]).reshape(&[2, 3]);
        let mask = Array::from_vec(vec![true, false, true, false, true, false]).reshape(&[2, 3]);

        let result = boolean_index(&arr, &mask).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![1, 3, 5]);
    }

    #[test]
    fn test_boolean_index_all_false() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
        let mask = Array::from_vec(vec![false; 5]);

        let result = boolean_index(&arr, &mask).expect("operation should succeed");

        assert_eq!(result.size(), 0);
    }

    #[test]
    fn test_boolean_index_all_true() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
        let mask = Array::from_vec(vec![true; 5]);

        let result = boolean_index(&arr, &mask).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_select_simple() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);

        let cond1 = arr.map(|x| x < 3);
        let choice1 = arr.map(|x| x * 10);

        let cond2 = arr.map(|x| x >= 3);
        let choice2 = arr.map(|x| x * 100);

        let result =
            select(&[cond1, cond2], &[choice1, choice2], 0).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![10, 20, 300, 400, 500]);
    }

    #[test]
    fn test_select_with_default() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);

        // Only one condition that matches some elements
        let cond = arr.map(|x| x > 3);
        let choice = arr.map(|x| x * 10);

        let result = select(&[cond], &[choice], -1).expect("operation should succeed");

        // Elements > 3 get multiplied by 10, others get -1
        assert_eq!(result.to_vec(), vec![-1, -1, -1, 40, 50]);
    }

    #[test]
    fn test_select_multiple_conditions() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);

        let cond1 = arr.map(|x| x == 1);
        let choice1 = Array::from_vec(vec![100, 100, 100, 100, 100]);

        let cond2 = arr.map(|x| x == 3);
        let choice2 = Array::from_vec(vec![300, 300, 300, 300, 300]);

        let cond3 = arr.map(|x| x == 5);
        let choice3 = Array::from_vec(vec![500, 500, 500, 500, 500]);

        let result = select(&[cond1, cond2, cond3], &[choice1, choice2, choice3], 0)
            .expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![100, 0, 300, 0, 500]);
    }

    #[test]
    fn test_select_2d() {
        let arr = Array::from_vec(vec![1, 2, 3, 4]).reshape(&[2, 2]);

        let cond1 = arr.map(|x| x < 3);
        let choice1 = arr.map(|x| x * 10);

        let cond2 = arr.map(|x| x >= 3);
        let choice2 = arr.map(|x| x * 100);

        let result =
            select(&[cond1, cond2], &[choice1, choice2], 0).expect("operation should succeed");

        assert_eq!(result.shape(), &[2, 2]);
        assert_eq!(result.to_vec(), vec![10, 20, 300, 400]);
    }

    #[test]
    fn test_select_mismatched_lengths() {
        let arr = Array::from_vec(vec![1, 2, 3]);

        let cond1 = arr.map(|x| x < 2);
        let choice1 = arr.map(|x| x * 10);

        let cond2 = arr.map(|x| x >= 2);
        let choice2 = arr.map(|x| x * 100);

        // 2 conditions but 3 choices
        let choice3 = arr.map(|x| x * 1000);

        let result = select(&[cond1, cond2], &[choice1, choice2, choice3], 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_select_mismatched_shapes() {
        let arr = Array::from_vec(vec![1, 2, 3, 4]);

        let cond1 = arr.map(|x| x < 3);
        let choice1 = arr.map(|x| x * 10);

        let cond2 = Array::from_vec(vec![true, false]); // Wrong shape
        let choice2 = arr.map(|x| x * 100);

        let result = select(&[cond1, cond2], &[choice1, choice2], 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_combined_indexing_take_and_boolean() {
        // First use take to reorder, then boolean mask
        let arr = Array::from_vec(vec![5, 2, 8, 1, 9, 3]);
        let indices = Array::from_vec(vec![0, 2, 4]); // [5, 8, 9]

        let reordered = take(&arr, &indices, None).expect("operation should succeed");
        let mask = reordered.map(|x| x > 7); // [false, true, true]

        let result = boolean_index(&reordered, &mask).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![8, 9]);
    }

    #[test]
    fn test_take_empty_indices() {
        let arr = Array::from_vec(vec![1, 2, 3, 4, 5]);
        let indices: Array<usize> = Array::from_vec(vec![]);

        let result = take(&arr, &indices, None).expect("operation should succeed");

        assert_eq!(result.size(), 0);
    }

    #[test]
    fn test_take_repeated_indices() {
        let arr = Array::from_vec(vec![10, 20, 30]);
        let indices = Array::from_vec(vec![0, 0, 1, 1, 2, 2]);

        let result = take(&arr, &indices, None).expect("operation should succeed");

        assert_eq!(result.to_vec(), vec![10, 10, 20, 20, 30, 30]);
    }
}