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
//! Advanced indexing operations for ndarray
//!
//! This module provides enhanced indexing capabilities including boolean
//! masking, fancy indexing, and advanced slicing operations similar to
//! `NumPy`'s advanced indexing functionality.

use ::ndarray::{Array, ArrayView, Ix1, Ix2};

/// Result type for coordinating indices
pub type IndicesResult = Result<(Array<usize, Ix1>, Array<usize, Ix1>), &'static str>;

/// Take elements from a 2D array along a given axis using indices from another array
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `indices` - Array of indices to take
/// * `axis` - The axis along which to take values (0 for rows, 1 for columns)
///
/// # Returns
///
/// A 2D array of values at the specified indices along the given axis
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::take_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6]];
/// let indices = array![0, 2];
/// let result = take_2d(a.view(), indices.view(), 1).expect("Operation failed");
/// assert_eq!(result.shape(), &[2, 2]);
/// assert_eq!(result[[0, 0]], 1);
/// assert_eq!(result[[0, 1]], 3);
/// ```
#[allow(dead_code)]
pub fn take_2d<T>(
    array: ArrayView<T, Ix2>,
    indices: ArrayView<usize, Ix1>,
    axis: usize,
) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone + Default,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);
    let axis_len = if axis == 0 { rows } else { cols };

    // Check that indices are within bounds
    for &idx in indices.iter() {
        if idx >= axis_len {
            return Err("Index out of bounds");
        }
    }

    // Create the result array with the appropriate shape
    let (result_rows, result_cols) = match axis {
        0 => (indices.len(), cols),
        1 => (rows, indices.len()),
        _ => return Err("Axis must be 0 or 1 for 2D arrays"),
    };

    let mut result = Array::<T, Ix2>::default((result_rows, result_cols));

    // Fill the result array
    match axis {
        0 => {
            // Take along rows
            for (i, &idx) in indices.iter().enumerate() {
                for j in 0..cols {
                    result[[i, j]] = array[[idx, j]].clone();
                }
            }
        }
        1 => {
            // Take along columns
            for i in 0..rows {
                for (j, &idx) in indices.iter().enumerate() {
                    result[[i, j]] = array[[i, idx]].clone();
                }
            }
        }
        _ => unreachable!(),
    }

    Ok(result)
}

/// Boolean mask indexing for 2D arrays
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `mask` - Boolean mask of the same shape as the array
///
/// # Returns
///
/// A 1D array containing the elements where the mask is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::boolean_mask_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6]];
/// let mask = array![[true, false, true], [false, true, false]];
/// let result = boolean_mask_2d(a.view(), mask.view()).expect("Operation failed");
/// assert_eq!(result.len(), 3);
/// assert_eq!(result[0], 1);
/// assert_eq!(result[1], 3);
/// assert_eq!(result[2], 5);
/// ```
#[allow(dead_code)]
pub fn boolean_mask_2d<T>(
    array: ArrayView<T, Ix2>,
    mask: ArrayView<bool, Ix2>,
) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
{
    // Check that the mask has the same shape as the array
    if array.shape() != mask.shape() {
        return Err("Mask shape must match array shape");
    }

    // Count the number of true values in the mask
    let true_count = mask.iter().filter(|&&x| x).count();

    // Create the result array
    let mut result = Array::<T, Ix1>::default(true_count);

    // Fill the result array with elements where the mask is true
    let mut idx = 0;
    for (val, &m) in array.iter().zip(mask.iter()) {
        if m {
            result[idx] = val.clone();
            idx += 1;
        }
    }

    Ok(result)
}

/// Boolean mask indexing for 1D arrays
///
/// # Arguments
///
/// * `array` - The input 1D array
/// * `mask` - Boolean mask of the same shape as the array
///
/// # Returns
///
/// A 1D array containing the elements where the mask is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::boolean_mask_1d;
///
/// let a = array![1, 2, 3, 4, 5];
/// let mask = array![true, false, true, false, true];
/// let result = boolean_mask_1d(a.view(), mask.view()).expect("Operation failed");
/// assert_eq!(result.len(), 3);
/// assert_eq!(result[0], 1);
/// assert_eq!(result[1], 3);
/// assert_eq!(result[2], 5);
/// ```
#[allow(dead_code)]
pub fn boolean_mask_1d<T>(
    array: ArrayView<T, Ix1>,
    mask: ArrayView<bool, Ix1>,
) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
{
    // Check that the mask has the same shape as the array
    if array.shape() != mask.shape() {
        return Err("Mask shape must match array shape");
    }

    // Count the number of true values in the mask
    let true_count = mask.iter().filter(|&&x| x).count();

    // Create the result array
    let mut result = Array::<T, Ix1>::default(true_count);

    // Fill the result array with elements where the mask is true
    let mut idx = 0;
    for (val, &m) in array.iter().zip(mask.iter()) {
        if m {
            result[idx] = val.clone();
            idx += 1;
        }
    }

    Ok(result)
}

/// Indexed slicing for 1D arrays
///
/// # Arguments
///
/// * `array` - The input 1D array
/// * `indices` - Array of indices to extract
///
/// # Returns
///
/// A 1D array containing the elements at the specified indices
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::take_1d;
///
/// let a = array![10, 20, 30, 40, 50];
/// let indices = array![0, 2, 4];
/// let result = take_1d(a.view(), indices.view()).expect("Operation failed");
/// assert_eq!(result.len(), 3);
/// assert_eq!(result[0], 10);
/// assert_eq!(result[1], 30);
/// assert_eq!(result[2], 50);
/// ```
#[allow(dead_code)]
pub fn take_1d<T>(
    array: ArrayView<T, Ix1>,
    indices: ArrayView<usize, Ix1>,
) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
{
    let len = array.len();

    // Verify that indices are in bounds
    for &idx in indices.iter() {
        if idx >= len {
            return Err("Index out of bounds");
        }
    }

    // Create the result array
    let mut result = Array::<T, Ix1>::default(indices.len());

    // Extract the elements at the specified indices
    for (i, &idx) in indices.iter().enumerate() {
        result[i] = array[idx].clone();
    }

    Ok(result)
}

/// Fancy indexing for 2D arrays with pairs of index arrays
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `row_indices` - Array of row indices
/// * `col_indices` - Array of column indices
///
/// # Returns
///
/// A 1D array containing the elements at the specified indices
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::fancy_index_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
/// let row_indices = array![0, 1, 2];
/// let col_indices = array![0, 1, 2];
/// let result = fancy_index_2d(a.view(), row_indices.view(), col_indices.view()).expect("Operation failed");
/// assert_eq!(result.len(), 3);
/// assert_eq!(result[0], 1);
/// assert_eq!(result[1], 5);
/// assert_eq!(result[2], 9);
/// ```
#[allow(dead_code)]
pub fn fancy_index_2d<T>(
    array: ArrayView<T, Ix2>,
    row_indices: ArrayView<usize, Ix1>,
    col_indices: ArrayView<usize, Ix1>,
) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
{
    // Check that all index arrays have the same length
    let result_size = row_indices.len();
    if col_indices.len() != result_size {
        return Err("Row and column index arrays must have the same length");
    }

    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // Check that _indices are within bounds
    for &idx in row_indices.iter() {
        if idx >= rows {
            return Err("Row index out of bounds");
        }
    }

    for &idx in col_indices.iter() {
        if idx >= cols {
            return Err("Column index out of bounds");
        }
    }

    // Create the result array
    let mut result = Array::<T, Ix1>::default(result_size);

    // Fill the result array
    for i in 0..result_size {
        let row = row_indices[i];
        let col = col_indices[i];
        result[i] = array[[row, col]].clone();
    }

    Ok(result)
}

/// Extract a diagonal or a sub-diagonal from a 2D array
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `offset` - Offset from the main diagonal (0 for main diagonal, positive for above, negative for below)
///
/// # Returns
///
/// A 1D array containing the diagonal elements
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::diagonal;
///
/// let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
///
/// // Main diagonal
/// let main_diag = diagonal(a.view(), 0).expect("Operation failed");
/// assert_eq!(main_diag.len(), 3);
/// assert_eq!(main_diag[0], 1);
/// assert_eq!(main_diag[1], 5);
/// assert_eq!(main_diag[2], 9);
///
/// // Upper diagonal
/// let upper_diag = diagonal(a.view(), 1).expect("Operation failed");
/// assert_eq!(upper_diag.len(), 2);
/// assert_eq!(upper_diag[0], 2);
/// assert_eq!(upper_diag[1], 6);
///
/// // Lower diagonal
/// let lower_diag = diagonal(a.view(), -1).expect("Operation failed");
/// assert_eq!(lower_diag.len(), 2);
/// assert_eq!(lower_diag[0], 4);
/// assert_eq!(lower_diag[1], 8);
/// ```
#[allow(dead_code)]
pub fn diagonal<T>(array: ArrayView<T, Ix2>, offset: isize) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // Calculate the length of the diagonal
    let diag_len = if offset >= 0 {
        std::cmp::min(rows, cols.saturating_sub(offset as usize))
    } else {
        std::cmp::min(cols, rows.saturating_sub((-offset) as usize))
    };

    if diag_len == 0 {
        return Err("No diagonal elements for the given offset");
    }

    // Create the result _array
    let mut result = Array::<T, Ix1>::default(diag_len);

    // Extract the diagonal elements
    for i in 0..diag_len {
        let row = if offset < 0 {
            i + (-offset) as usize
        } else {
            i
        };

        let col = if offset > 0 { i + offset as usize } else { i };

        result[i] = array[[row, col]].clone();
    }

    Ok(result)
}

/// Where function - select elements based on a condition for 1D arrays
///
/// # Arguments
///
/// * `array` - The input 1D array
/// * `condition` - A function that takes a reference to an element and returns a bool
///
/// # Returns
///
/// A 1D array containing the elements where the condition is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::where_1d;
///
/// let a = array![1, 2, 3, 4, 5];
/// let result = where_1d(a.view(), |&x| x > 3).expect("Operation failed");
/// assert_eq!(result.len(), 2);
/// assert_eq!(result[0], 4);
/// assert_eq!(result[1], 5);
/// ```
#[allow(dead_code)]
pub fn where_1d<T, F>(array: ArrayView<T, Ix1>, condition: F) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
    F: Fn(&T) -> bool,
{
    // Build a boolean mask _array based on the condition
    let mask = array.map(condition);

    // Use the boolean_mask_1d function to select elements
    boolean_mask_1d(array, mask.view())
}

/// Where function - select elements based on a condition for 2D arrays
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `condition` - A function that takes a reference to an element and returns a bool
///
/// # Returns
///
/// A 1D array containing the elements where the condition is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::where_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6]];
/// let result = where_2d(a.view(), |&x| x > 3).expect("Operation failed");
/// assert_eq!(result.len(), 3);
/// assert_eq!(result[0], 4);
/// assert_eq!(result[1], 5);
/// assert_eq!(result[2], 6);
/// ```
#[allow(dead_code)]
pub fn where_2d<T, F>(array: ArrayView<T, Ix2>, condition: F) -> Result<Array<T, Ix1>, &'static str>
where
    T: Clone + Default,
    F: Fn(&T) -> bool,
{
    // Build a boolean mask _array based on the condition
    let mask = array.map(condition);

    // Use the boolean_mask_2d function to select elements
    boolean_mask_2d(array, mask.view())
}

/// Extract indices where a 1D array meets a condition
///
/// # Arguments
///
/// * `array` - The input 1D array
/// * `condition` - A function that takes a reference to an element and returns a bool
///
/// # Returns
///
/// A 1D array of indices where the condition is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::indices_where_1d;
///
/// let a = array![10, 20, 30, 40, 50];
/// let result = indices_where_1d(a.view(), |&x| x > 30).expect("Operation failed");
/// assert_eq!(result.len(), 2);
/// assert_eq!(result[0], 3);
/// assert_eq!(result[1], 4);
/// ```
#[allow(dead_code)]
pub fn indices_where_1d<T, F>(
    array: ArrayView<T, Ix1>,
    condition: F,
) -> Result<Array<usize, Ix1>, &'static str>
where
    T: Clone,
    F: Fn(&T) -> bool,
{
    // Build a vector of indices where the condition is true
    let mut indices = Vec::new();

    for (i, val) in array.iter().enumerate() {
        if condition(val) {
            indices.push(i);
        }
    }

    // Convert the vector to an ndarray Array
    Ok(Array::from_vec(indices))
}

/// Extract indices where a 2D array meets a condition
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `condition` - A function that takes a reference to an element and returns a bool
///
/// # Returns
///
/// A tuple of two 1D arrays (row_indices, col_indices) where the condition is true
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::indices_where_2d;
///
/// let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
/// let (rows, cols) = indices_where_2d(a.view(), |&x| x > 5).expect("Operation failed");
/// assert_eq!(rows.len(), 4);
/// assert_eq!(cols.len(), 4);
/// // The indices correspond to elements: 6, 7, 8, 9
/// ```
#[allow(dead_code)]
pub fn indices_where_2d<T, F>(array: ArrayView<T, Ix2>, condition: F) -> IndicesResult
where
    T: Clone,
    F: Fn(&T) -> bool,
{
    let (rows, cols) = (array.shape()[0], array.shape()[1]);

    // Build vectors of row and column indices where the condition is true
    let mut row_indices = Vec::new();
    let mut col_indices = Vec::new();

    for r in 0..rows {
        for c in 0..cols {
            if condition(&array[[r, c]]) {
                row_indices.push(r);
                col_indices.push(c);
            }
        }
    }

    // Convert the vectors to ndarray Arrays
    Ok((Array::from_vec(row_indices), Array::from_vec(col_indices)))
}

/// Return elements from a 2D array along an axis at specified indices
///
/// # Arguments
///
/// * `array` - The input 2D array
/// * `indices` - Indices to take along the specified axis
/// * `axis` - The axis along which to take values (0 for rows, 1 for columns)
///
/// # Returns
///
/// A 2D array with selected slices from the original array
///
/// # Examples
///
/// ```
/// use ::ndarray::array;
/// use scirs2_core::ndarray_ext::indexing::take_along_axis;
///
/// let a = array![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
/// let indices = array![0, 2];
///
/// // Take rows 0 and 2
/// let result = take_along_axis(a.view(), indices.view(), 0).expect("Operation failed");
/// assert_eq!(result.shape(), &[2, 3]);
/// assert_eq!(result[[0, 0]], 1);
/// assert_eq!(result[[0, 1]], 2);
/// assert_eq!(result[[0, 2]], 3);
/// assert_eq!(result[[1, 0]], 7);
/// assert_eq!(result[[1, 1]], 8);
/// assert_eq!(result[[1, 2]], 9);
/// ```
#[allow(dead_code)]
pub fn take_along_axis<T>(
    array: ArrayView<T, Ix2>,
    indices: ArrayView<usize, Ix1>,
    axis: usize,
) -> Result<Array<T, Ix2>, &'static str>
where
    T: Clone + Default,
{
    take_2d(array, indices, axis)
}

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

    #[test]
    fn test_boolean_mask_1d() {
        let a = array![1, 2, 3, 4, 5];
        let mask = array![true, false, true, false, true];

        let result = boolean_mask_1d(a.view(), mask.view()).expect("Operation failed");
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], 1);
        assert_eq!(result[1], 3);
        assert_eq!(result[2], 5);
    }

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

        let result = boolean_mask_2d(a.view(), mask.view()).expect("Operation failed");
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], 1);
        assert_eq!(result[1], 3);
        assert_eq!(result[2], 5);
    }

    #[test]
    fn test_take_1d() {
        let a = array![10, 20, 30, 40, 50];
        let indices = array![0, 2, 4];

        let result = take_1d(a.view(), indices.view()).expect("Operation failed");
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], 10);
        assert_eq!(result[1], 30);
        assert_eq!(result[2], 50);
    }

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

        // Take along axis 0 (rows)
        let result = take_2d(a.view(), indices.view(), 0).expect("Operation failed");
        assert_eq!(result.shape(), &[2, 3]);
        assert_eq!(result[[0, 0]], 1);
        assert_eq!(result[[0, 1]], 2);
        assert_eq!(result[[0, 2]], 3);
        assert_eq!(result[[1, 0]], 7);
        assert_eq!(result[[1, 1]], 8);
        assert_eq!(result[[1, 2]], 9);

        // Take along axis 1 (columns)
        let result = take_2d(a.view(), indices.view(), 1).expect("Operation failed");
        assert_eq!(result.shape(), &[3, 2]);
        assert_eq!(result[[0, 0]], 1);
        assert_eq!(result[[0, 1]], 3);
        assert_eq!(result[[1, 0]], 4);
        assert_eq!(result[[1, 1]], 6);
        assert_eq!(result[[2, 0]], 7);
        assert_eq!(result[[2, 1]], 9);
    }

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

        let result = fancy_index_2d(a.view(), row_indices.view(), col_indices.view())
            .expect("Operation failed");
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], 1);
        assert_eq!(result[1], 8);
    }

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

        // Main diagonal
        let main_diag = diagonal(a.view(), 0).expect("Operation failed");
        assert_eq!(main_diag.len(), 3);
        assert_eq!(main_diag[0], 1);
        assert_eq!(main_diag[1], 5);
        assert_eq!(main_diag[2], 9);

        // Upper diagonal
        let upper_diag = diagonal(a.view(), 1).expect("Operation failed");
        assert_eq!(upper_diag.len(), 2);
        assert_eq!(upper_diag[0], 2);
        assert_eq!(upper_diag[1], 6);

        // Lower diagonal
        let lower_diag = diagonal(a.view(), -1).expect("Operation failed");
        assert_eq!(lower_diag.len(), 2);
        assert_eq!(lower_diag[0], 4);
        assert_eq!(lower_diag[1], 8);
    }

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

        let result = where_1d(a.view(), |&x| x > 3).expect("Operation failed");
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], 4);
        assert_eq!(result[1], 5);
    }

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

        let result = where_2d(a.view(), |&x| x > 3).expect("Operation failed");
        assert_eq!(result.len(), 3);
        assert_eq!(result[0], 4);
        assert_eq!(result[1], 5);
        assert_eq!(result[2], 6);
    }

    #[test]
    fn test_indices_where_1d() {
        let a = array![10, 20, 30, 40, 50];

        let result = indices_where_1d(a.view(), |&x| x > 30).expect("Operation failed");
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], 3);
        assert_eq!(result[1], 4);
    }

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

        let (rows, cols) = indices_where_2d(a.view(), |&x| x > 5).expect("Operation failed");
        assert_eq!(rows.len(), 4);
        assert_eq!(cols.len(), 4);

        // Verify that the indices correspond to the expected elements
        for (r, c) in rows.iter().zip(cols.iter()) {
            assert!(a[[*r, *c]] > 5);
        }
    }

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

        // Test along axis 0 (rows)
        let result = take_along_axis(a.view(), indices.view(), 0).expect("Operation failed");
        assert_eq!(result.shape(), &[2, 3]);
        assert_eq!(result[[0, 0]], 1);
        assert_eq!(result[[0, 1]], 2);
        assert_eq!(result[[0, 2]], 3);
        assert_eq!(result[[1, 0]], 7);
        assert_eq!(result[[1, 1]], 8);
        assert_eq!(result[[1, 2]], 9);
    }
}