ferray-core 0.2.8

N-dimensional array type and foundational primitives for ferray
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
// ferray-core: Basic indexing (REQ-12, REQ-14)
//
// Integer + slice indexing returning views (zero-copy).
// insert_axis / remove_axis for dimension manipulation.
//
// These are implemented as methods on Array, ArrayView, ArrayViewMut.
// The s![] macro is out of scope (Agent 1d).

use crate::array::owned::Array;
use crate::array::view::ArrayView;
use crate::array::view_mut::ArrayViewMut;
use crate::dimension::{Axis, Dimension, IxDyn};
use crate::dtype::Element;
use crate::error::{FerrayError, FerrayResult};

/// Normalize a potentially negative index to a positive one.
///
/// Negative indices count from the end: -1 is the last element, -2 is
/// second-to-last, etc. Returns `Err` if the normalized index is out of
/// bounds.
fn normalize_index(index: isize, size: usize, axis: usize) -> FerrayResult<usize> {
    let normalized = if index < 0 {
        let pos = size as isize + index;
        if pos < 0 {
            return Err(FerrayError::index_out_of_bounds(index, axis, size));
        }
        pos as usize
    } else {
        let idx = index as usize;
        if idx >= size {
            return Err(FerrayError::index_out_of_bounds(index, axis, size));
        }
        idx
    };
    Ok(normalized)
}

/// A slice specification for one axis, mirroring Python's `start:stop:step`.
///
/// All fields are optional (represented by `None`), matching NumPy behaviour:
/// - `start`: defaults to 0 (or end-1 if step < 0)
/// - `stop`: defaults to size (or before-start if step < 0)
/// - `step`: defaults to 1; must not be 0
#[derive(Debug, Clone, Copy)]
pub struct SliceSpec {
    /// Start index (inclusive). Negative counts from end.
    pub start: Option<isize>,
    /// Stop index (exclusive). Negative counts from end.
    pub stop: Option<isize>,
    /// Step size. Must not be zero.
    pub step: Option<isize>,
}

impl SliceSpec {
    /// Create a new full-range slice (equivalent to `:`).
    pub fn full() -> Self {
        Self {
            start: None,
            stop: None,
            step: None,
        }
    }

    /// Create a slice `start:stop` with step 1.
    pub fn new(start: isize, stop: isize) -> Self {
        Self {
            start: Some(start),
            stop: Some(stop),
            step: None,
        }
    }

    /// Create a slice `start:stop:step`.
    pub fn with_step(start: isize, stop: isize, step: isize) -> Self {
        Self {
            start: Some(start),
            stop: Some(stop),
            step: Some(step),
        }
    }

    /// Validate that the step is not zero.
    fn validate(&self) -> FerrayResult<()> {
        if let Some(0) = self.step {
            return Err(FerrayError::invalid_value("slice step cannot be zero"));
        }
        Ok(())
    }

    /// Convert to an ndarray Slice.
    #[allow(clippy::wrong_self_convention)]
    fn to_ndarray_slice(&self) -> ndarray::Slice {
        ndarray::Slice::new(self.start.unwrap_or(0), self.stop, self.step.unwrap_or(1))
    }

    /// Convert to an ndarray SliceInfoElem (used by s![] macro integration).
    #[allow(dead_code, clippy::wrong_self_convention)]
    pub(crate) fn to_ndarray_elem(&self) -> ndarray::SliceInfoElem {
        ndarray::SliceInfoElem::Slice {
            start: self.start.unwrap_or(0),
            end: self.stop,
            step: self.step.unwrap_or(1),
        }
    }
}

// ---------------------------------------------------------------------------
// Array methods — basic indexing
// ---------------------------------------------------------------------------

impl<T: Element, D: Dimension> Array<T, D> {
    /// Index into the array along a given axis, removing that axis.
    ///
    /// Equivalent to `a[i]` for axis 0, or `a[:, i]` for axis 1, etc.
    /// Returns a view with one fewer dimension (dynamic-rank).
    ///
    /// # Errors
    /// - `AxisOutOfBounds` if `axis >= ndim`
    /// - `IndexOutOfBounds` if `index` is out of range (supports negative)
    pub fn index_axis(&self, axis: Axis, index: isize) -> FerrayResult<ArrayView<'_, T, IxDyn>>
    where
        D::NdarrayDim: ndarray::RemoveAxis,
    {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        let size = self.shape()[ax];
        let idx = normalize_index(index, size, ax)?;

        let nd_axis = ndarray::Axis(ax);
        let sub = self.inner.index_axis(nd_axis, idx);
        let dyn_view = sub.into_dyn();
        Ok(ArrayView::from_ndarray(dyn_view))
    }

    /// Slice the array along a given axis, returning a view.
    ///
    /// The returned view shares data with the source (zero-copy).
    ///
    /// # Errors
    /// - `AxisOutOfBounds` if `axis >= ndim`
    /// - `InvalidValue` if step is zero
    pub fn slice_axis(&self, axis: Axis, spec: SliceSpec) -> FerrayResult<ArrayView<'_, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        spec.validate()?;

        let nd_axis = ndarray::Axis(ax);
        let nd_slice = spec.to_ndarray_slice();
        let sliced = self.inner.slice_axis(nd_axis, nd_slice);
        let dyn_view = sliced.into_dyn();
        Ok(ArrayView::from_ndarray(dyn_view))
    }

    /// Slice the array along a given axis, returning a mutable view.
    ///
    /// # Errors
    /// Same as [`slice_axis`](Self::slice_axis).
    pub fn slice_axis_mut(
        &mut self,
        axis: Axis,
        spec: SliceSpec,
    ) -> FerrayResult<ArrayViewMut<'_, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        spec.validate()?;

        let nd_axis = ndarray::Axis(ax);
        let nd_slice = spec.to_ndarray_slice();
        let sliced = self.inner.slice_axis_mut(nd_axis, nd_slice);
        let dyn_view = sliced.into_dyn();
        Ok(ArrayViewMut::from_ndarray(dyn_view))
    }

    /// Multi-axis slicing: apply a slice specification to each axis.
    ///
    /// `specs` must have length equal to `ndim()`. For axes you don't
    /// want to slice, pass `SliceSpec::full()`.
    ///
    /// # Errors
    /// - `InvalidValue` if `specs.len() != ndim()`
    /// - Any errors from individual axis slicing
    pub fn slice_multi(&self, specs: &[SliceSpec]) -> FerrayResult<ArrayView<'_, T, IxDyn>> {
        let ndim = self.ndim();
        if specs.len() != ndim {
            return Err(FerrayError::invalid_value(format!(
                "expected {} slice specs, got {}",
                ndim,
                specs.len()
            )));
        }

        for spec in specs {
            spec.validate()?;
        }

        // Apply axis-by-axis slicing using move variants to preserve lifetimes
        let mut result = self.inner.view().into_dyn();
        for (ax, spec) in specs.iter().enumerate() {
            let nd_axis = ndarray::Axis(ax);
            let nd_slice = spec.to_ndarray_slice();
            result = result.slice_axis_move(nd_axis, nd_slice).into_dyn();
        }
        Ok(ArrayView::from_ndarray(result))
    }

    /// Insert a new axis of length 1 at the given position.
    ///
    /// This is equivalent to `np.expand_dims` or `np.newaxis`.
    /// Returns a dynamic-rank view with one more dimension.
    ///
    /// # Errors
    /// - `AxisOutOfBounds` if `axis > ndim`
    pub fn insert_axis(&self, axis: Axis) -> FerrayResult<ArrayView<'_, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax > ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim + 1));
        }

        let dyn_view = self.inner.view().into_dyn();
        let expanded = dyn_view.insert_axis(ndarray::Axis(ax));
        Ok(ArrayView::from_ndarray(expanded))
    }

    /// Remove an axis of length 1.
    ///
    /// This is equivalent to `np.squeeze` for a single axis.
    /// Returns a dynamic-rank view with one fewer dimension.
    ///
    /// # Errors
    /// - `AxisOutOfBounds` if `axis >= ndim`
    /// - `InvalidValue` if the axis has size != 1
    pub fn remove_axis(&self, axis: Axis) -> FerrayResult<ArrayView<'_, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        if self.shape()[ax] != 1 {
            return Err(FerrayError::invalid_value(format!(
                "cannot remove axis {} with size {} (must be 1)",
                ax,
                self.shape()[ax]
            )));
        }

        // index_axis_move at 0 removes the axis (consumes the view, preserving lifetime)
        let dyn_view = self.inner.view().into_dyn();
        let squeezed = dyn_view.index_axis_move(ndarray::Axis(ax), 0);
        Ok(ArrayView::from_ndarray(squeezed))
    }

    /// Index into the array with a flat (linear) index.
    ///
    /// Elements are ordered in row-major (C) order.
    ///
    /// # Errors
    /// Returns `IndexOutOfBounds` if the index is out of range.
    pub fn flat_index(&self, index: isize) -> FerrayResult<&T> {
        let size = self.size();
        let idx = normalize_index(index, size, 0)?;
        self.inner
            .iter()
            .nth(idx)
            .ok_or_else(|| FerrayError::index_out_of_bounds(index, 0, size))
    }

    /// Get a reference to a single element by multi-dimensional index.
    ///
    /// Supports negative indices (counting from end).
    ///
    /// # Errors
    /// - `InvalidValue` if `indices.len() != ndim()`
    /// - `IndexOutOfBounds` if any index is out of range
    pub fn get(&self, indices: &[isize]) -> FerrayResult<&T> {
        let ndim = self.ndim();
        if indices.len() != ndim {
            return Err(FerrayError::invalid_value(format!(
                "expected {} indices, got {}",
                ndim,
                indices.len()
            )));
        }

        // Compute the flat offset manually
        let shape = self.shape();
        let strides = self.inner.strides();
        let base_ptr = self.inner.as_ptr();

        let mut offset: isize = 0;
        for (ax, &idx) in indices.iter().enumerate() {
            let pos = normalize_index(idx, shape[ax], ax)?;
            offset += pos as isize * strides[ax];
        }

        // SAFETY: all indices are validated in-bounds, so the computed
        // offset is within the array's data allocation.
        Ok(unsafe { &*base_ptr.offset(offset) })
    }

    /// Get a mutable reference to a single element by multi-dimensional index.
    ///
    /// # Errors
    /// Same as [`get`](Self::get).
    pub fn get_mut(&mut self, indices: &[isize]) -> FerrayResult<&mut T> {
        let ndim = self.ndim();
        if indices.len() != ndim {
            return Err(FerrayError::invalid_value(format!(
                "expected {} indices, got {}",
                ndim,
                indices.len()
            )));
        }

        let shape = self.shape().to_vec();
        let strides: Vec<isize> = self.inner.strides().to_vec();
        let base_ptr = self.inner.as_mut_ptr();

        let mut offset: isize = 0;
        for (ax, &idx) in indices.iter().enumerate() {
            let pos = normalize_index(idx, shape[ax], ax)?;
            offset += pos as isize * strides[ax];
        }

        // SAFETY: we have &mut self so exclusive access is guaranteed,
        // and all indices are validated in-bounds.
        Ok(unsafe { &mut *base_ptr.offset(offset) })
    }
}

// ---------------------------------------------------------------------------
// ArrayView methods — basic indexing
// ---------------------------------------------------------------------------

impl<'a, T: Element, D: Dimension> ArrayView<'a, T, D> {
    /// Index into the view along a given axis, removing that axis.
    pub fn index_axis(&self, axis: Axis, index: isize) -> FerrayResult<ArrayView<'a, T, IxDyn>>
    where
        D::NdarrayDim: ndarray::RemoveAxis,
    {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        let size = self.shape()[ax];
        let idx = normalize_index(index, size, ax)?;

        let nd_axis = ndarray::Axis(ax);
        // clone() on ArrayView is cheap (it's Copy-like)
        let sub = self.inner.clone().index_axis_move(nd_axis, idx);
        let dyn_view = sub.into_dyn();
        Ok(ArrayView::from_ndarray(dyn_view))
    }

    /// Slice the view along a given axis.
    pub fn slice_axis(&self, axis: Axis, spec: SliceSpec) -> FerrayResult<ArrayView<'a, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        spec.validate()?;

        let nd_axis = ndarray::Axis(ax);
        let nd_slice = spec.to_ndarray_slice();
        // slice_axis on a cloned view preserves the 'a lifetime
        let sliced = self.inner.clone().slice_axis_move(nd_axis, nd_slice);
        let dyn_view = sliced.into_dyn();
        Ok(ArrayView::from_ndarray(dyn_view))
    }

    /// Insert a new axis of length 1 at the given position.
    pub fn insert_axis(&self, axis: Axis) -> FerrayResult<ArrayView<'a, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax > ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim + 1));
        }

        let dyn_view = self.inner.clone().into_dyn();
        let expanded = dyn_view.insert_axis(ndarray::Axis(ax));
        Ok(ArrayView::from_ndarray(expanded))
    }

    /// Remove an axis of length 1.
    pub fn remove_axis(&self, axis: Axis) -> FerrayResult<ArrayView<'a, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        if self.shape()[ax] != 1 {
            return Err(FerrayError::invalid_value(format!(
                "cannot remove axis {} with size {} (must be 1)",
                ax,
                self.shape()[ax]
            )));
        }

        let dyn_view = self.inner.clone().into_dyn();
        let squeezed = dyn_view.index_axis_move(ndarray::Axis(ax), 0);
        Ok(ArrayView::from_ndarray(squeezed))
    }

    /// Get a reference to a single element by multi-dimensional index.
    pub fn get(&self, indices: &[isize]) -> FerrayResult<&'a T> {
        let ndim = self.ndim();
        if indices.len() != ndim {
            return Err(FerrayError::invalid_value(format!(
                "expected {} indices, got {}",
                ndim,
                indices.len()
            )));
        }

        let shape = self.shape();
        let strides = self.inner.strides();
        let base_ptr = self.inner.as_ptr();

        let mut offset: isize = 0;
        for (ax, &idx) in indices.iter().enumerate() {
            let pos = normalize_index(idx, shape[ax], ax)?;
            offset += pos as isize * strides[ax];
        }

        // SAFETY: indices validated in-bounds; the pointer is valid for 'a.
        Ok(unsafe { &*base_ptr.offset(offset) })
    }
}

// ---------------------------------------------------------------------------
// ArrayViewMut methods — basic indexing
// ---------------------------------------------------------------------------

impl<'a, T: Element, D: Dimension> ArrayViewMut<'a, T, D> {
    /// Slice the mutable view along a given axis.
    pub fn slice_axis_mut(
        &mut self,
        axis: Axis,
        spec: SliceSpec,
    ) -> FerrayResult<ArrayViewMut<'_, T, IxDyn>> {
        let ndim = self.ndim();
        let ax = axis.index();
        if ax >= ndim {
            return Err(FerrayError::axis_out_of_bounds(ax, ndim));
        }
        spec.validate()?;

        let nd_axis = ndarray::Axis(ax);
        let nd_slice = spec.to_ndarray_slice();
        let sliced = self.inner.slice_axis_mut(nd_axis, nd_slice);
        let dyn_view = sliced.into_dyn();
        Ok(ArrayViewMut::from_ndarray(dyn_view))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dimension::{Ix1, Ix2, Ix3};

    // -----------------------------------------------------------------------
    // Normalization
    // -----------------------------------------------------------------------

    #[test]
    fn normalize_positive_in_bounds() {
        assert_eq!(normalize_index(2, 5, 0).unwrap(), 2);
    }

    #[test]
    fn normalize_negative() {
        assert_eq!(normalize_index(-1, 5, 0).unwrap(), 4);
        assert_eq!(normalize_index(-5, 5, 0).unwrap(), 0);
    }

    #[test]
    fn normalize_out_of_bounds() {
        assert!(normalize_index(5, 5, 0).is_err());
        assert!(normalize_index(-6, 5, 0).is_err());
    }

    // -----------------------------------------------------------------------
    // index_axis
    // -----------------------------------------------------------------------

    #[test]
    fn index_axis_row() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        let row = arr.index_axis(Axis(0), 1).unwrap();
        assert_eq!(row.shape(), &[4]);
        let data: Vec<i32> = row.iter().copied().collect();
        assert_eq!(data, vec![4, 5, 6, 7]);
    }

    #[test]
    fn index_axis_column() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        let col = arr.index_axis(Axis(1), 2).unwrap();
        assert_eq!(col.shape(), &[3]);
        let data: Vec<i32> = col.iter().copied().collect();
        assert_eq!(data, vec![2, 6, 10]);
    }

    #[test]
    fn index_axis_negative() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        let row = arr.index_axis(Axis(0), -1).unwrap();
        let data: Vec<i32> = row.iter().copied().collect();
        assert_eq!(data, vec![8, 9, 10, 11]);
    }

    #[test]
    fn index_axis_out_of_bounds() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        assert!(arr.index_axis(Axis(0), 3).is_err());
        assert!(arr.index_axis(Axis(2), 0).is_err());
    }

    #[test]
    fn index_axis_is_zero_copy() {
        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
            .unwrap();
        let row = arr.index_axis(Axis(0), 0).unwrap();
        assert_eq!(row.as_ptr(), arr.as_ptr());
    }

    // -----------------------------------------------------------------------
    // slice_axis
    // -----------------------------------------------------------------------

    #[test]
    fn slice_axis_basic() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![10, 20, 30, 40, 50]).unwrap();
        let sliced = arr.slice_axis(Axis(0), SliceSpec::new(1, 4)).unwrap();
        assert_eq!(sliced.shape(), &[3]);
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![20, 30, 40]);
    }

    #[test]
    fn slice_axis_step() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([6]), vec![0, 1, 2, 3, 4, 5]).unwrap();
        let sliced = arr
            .slice_axis(Axis(0), SliceSpec::with_step(0, 6, 2))
            .unwrap();
        assert_eq!(sliced.shape(), &[3]);
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![0, 2, 4]);
    }

    #[test]
    fn slice_axis_negative_step() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![0, 1, 2, 3, 4]).unwrap();
        // Reverse the entire array: range [0, len) traversed backwards
        // ndarray interprets Slice::new(start, end, step) where start/end define
        // a forward range and negative step reverses traversal within it.
        let spec = SliceSpec {
            start: None,
            stop: None,
            step: Some(-1),
        };
        let sliced = arr.slice_axis(Axis(0), spec).unwrap();
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![4, 3, 2, 1, 0]);
    }

    #[test]
    fn slice_axis_negative_step_partial() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![0, 1, 2, 3, 4]).unwrap();
        // Range [1, 4) traversed backwards with step -1: [3, 2, 1]
        let sliced = arr
            .slice_axis(Axis(0), SliceSpec::with_step(1, 4, -1))
            .unwrap();
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![3, 2, 1]);
    }

    #[test]
    fn slice_axis_full() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([3]), vec![1, 2, 3]).unwrap();
        let sliced = arr.slice_axis(Axis(0), SliceSpec::full()).unwrap();
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![1, 2, 3]);
    }

    #[test]
    fn slice_axis_2d_rows() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([4, 3]), (0..12).collect()).unwrap();
        let sliced = arr.slice_axis(Axis(0), SliceSpec::new(1, 3)).unwrap();
        assert_eq!(sliced.shape(), &[2, 3]);
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![3, 4, 5, 6, 7, 8]);
    }

    #[test]
    fn slice_axis_is_zero_copy() {
        let arr =
            Array::<f64, Ix1>::from_vec(Ix1::new([5]), vec![1.0, 2.0, 3.0, 4.0, 5.0]).unwrap();
        let sliced = arr.slice_axis(Axis(0), SliceSpec::new(1, 4)).unwrap();
        unsafe {
            assert_eq!(*sliced.as_ptr(), 2.0);
        }
    }

    #[test]
    fn slice_axis_zero_step_error() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([3]), vec![1, 2, 3]).unwrap();
        assert!(
            arr.slice_axis(Axis(0), SliceSpec::with_step(0, 3, 0))
                .is_err()
        );
    }

    // -----------------------------------------------------------------------
    // slice_multi
    // -----------------------------------------------------------------------

    #[test]
    fn slice_multi_2d() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([4, 5]), (0..20).collect()).unwrap();
        let sliced = arr
            .slice_multi(&[SliceSpec::new(1, 3), SliceSpec::new(0, 4)])
            .unwrap();
        assert_eq!(sliced.shape(), &[2, 4]);
    }

    #[test]
    fn slice_multi_wrong_count() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([2, 3]), (0..6).collect()).unwrap();
        assert!(arr.slice_multi(&[SliceSpec::full()]).is_err());
    }

    // -----------------------------------------------------------------------
    // insert_axis / remove_axis
    // -----------------------------------------------------------------------

    #[test]
    fn insert_axis_at_front() {
        let arr = Array::<f64, Ix1>::from_vec(Ix1::new([3]), vec![1.0, 2.0, 3.0]).unwrap();
        let expanded = arr.insert_axis(Axis(0)).unwrap();
        assert_eq!(expanded.shape(), &[1, 3]);
    }

    #[test]
    fn insert_axis_at_end() {
        let arr = Array::<f64, Ix1>::from_vec(Ix1::new([3]), vec![1.0, 2.0, 3.0]).unwrap();
        let expanded = arr.insert_axis(Axis(1)).unwrap();
        assert_eq!(expanded.shape(), &[3, 1]);
    }

    #[test]
    fn insert_axis_out_of_bounds() {
        let arr = Array::<f64, Ix1>::from_vec(Ix1::new([3]), vec![1.0, 2.0, 3.0]).unwrap();
        assert!(arr.insert_axis(Axis(3)).is_err());
    }

    #[test]
    fn remove_axis_single() {
        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([1, 3]), vec![1.0, 2.0, 3.0]).unwrap();
        let squeezed = arr.remove_axis(Axis(0)).unwrap();
        assert_eq!(squeezed.shape(), &[3]);
        let data: Vec<f64> = squeezed.iter().copied().collect();
        assert_eq!(data, vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn remove_axis_not_one() {
        let arr = Array::<f64, Ix2>::from_vec(Ix2::new([2, 3]), vec![1.0; 6]).unwrap();
        assert!(arr.remove_axis(Axis(0)).is_err());
    }

    #[test]
    fn remove_axis_out_of_bounds() {
        let arr = Array::<f64, Ix1>::from_vec(Ix1::new([3]), vec![1.0, 2.0, 3.0]).unwrap();
        assert!(arr.remove_axis(Axis(1)).is_err());
    }

    // -----------------------------------------------------------------------
    // flat_index
    // -----------------------------------------------------------------------

    #[test]
    fn flat_index_positive() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([2, 3]), vec![1, 2, 3, 4, 5, 6]).unwrap();
        assert_eq!(*arr.flat_index(0).unwrap(), 1);
        assert_eq!(*arr.flat_index(3).unwrap(), 4);
        assert_eq!(*arr.flat_index(5).unwrap(), 6);
    }

    #[test]
    fn flat_index_negative() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![10, 20, 30, 40, 50]).unwrap();
        assert_eq!(*arr.flat_index(-1).unwrap(), 50);
        assert_eq!(*arr.flat_index(-5).unwrap(), 10);
    }

    #[test]
    fn flat_index_out_of_bounds() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([3]), vec![1, 2, 3]).unwrap();
        assert!(arr.flat_index(3).is_err());
        assert!(arr.flat_index(-4).is_err());
    }

    // -----------------------------------------------------------------------
    // get / get_mut
    // -----------------------------------------------------------------------

    #[test]
    fn get_2d() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        assert_eq!(*arr.get(&[0, 0]).unwrap(), 0);
        assert_eq!(*arr.get(&[1, 2]).unwrap(), 6);
        assert_eq!(*arr.get(&[2, 3]).unwrap(), 11);
    }

    #[test]
    fn get_negative_indices() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        assert_eq!(*arr.get(&[-1, -1]).unwrap(), 11);
        assert_eq!(*arr.get(&[-3, 0]).unwrap(), 0);
    }

    #[test]
    fn get_wrong_ndim() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([2, 3]), (0..6).collect()).unwrap();
        assert!(arr.get(&[0]).is_err());
        assert!(arr.get(&[0, 0, 0]).is_err());
    }

    #[test]
    fn get_mut_modify() {
        let mut arr =
            Array::<i32, Ix2>::from_vec(Ix2::new([2, 3]), vec![1, 2, 3, 4, 5, 6]).unwrap();
        *arr.get_mut(&[1, 2]).unwrap() = 99;
        assert_eq!(*arr.get(&[1, 2]).unwrap(), 99);
    }

    // -----------------------------------------------------------------------
    // ArrayView basic indexing
    // -----------------------------------------------------------------------

    #[test]
    fn view_index_axis() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([3, 4]), (0..12).collect()).unwrap();
        let v = arr.view();
        let row = v.index_axis(Axis(0), 1).unwrap();
        let data: Vec<i32> = row.iter().copied().collect();
        assert_eq!(data, vec![4, 5, 6, 7]);
    }

    #[test]
    fn view_slice_axis() {
        let arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![10, 20, 30, 40, 50]).unwrap();
        let v = arr.view();
        let sliced = v.slice_axis(Axis(0), SliceSpec::new(1, 4)).unwrap();
        let data: Vec<i32> = sliced.iter().copied().collect();
        assert_eq!(data, vec![20, 30, 40]);
    }

    #[test]
    fn view_insert_remove_axis() {
        let arr = Array::<f64, Ix1>::from_vec(Ix1::new([4]), vec![1.0, 2.0, 3.0, 4.0]).unwrap();
        let v = arr.view();
        let expanded = v.insert_axis(Axis(0)).unwrap();
        assert_eq!(expanded.shape(), &[1, 4]);
        let squeezed = expanded.remove_axis(Axis(0)).unwrap();
        assert_eq!(squeezed.shape(), &[4]);
    }

    #[test]
    fn view_get() {
        let arr = Array::<i32, Ix2>::from_vec(Ix2::new([2, 3]), vec![1, 2, 3, 4, 5, 6]).unwrap();
        let v = arr.view();
        assert_eq!(*v.get(&[1, 2]).unwrap(), 6);
    }

    // -----------------------------------------------------------------------
    // ArrayViewMut slice
    // -----------------------------------------------------------------------

    #[test]
    fn view_mut_slice_axis() {
        let mut arr = Array::<i32, Ix1>::from_vec(Ix1::new([5]), vec![1, 2, 3, 4, 5]).unwrap();
        {
            let mut vm = arr.view_mut();
            let mut sliced = vm.slice_axis_mut(Axis(0), SliceSpec::new(1, 3)).unwrap();
            if let Some(s) = sliced.as_slice_mut() {
                s[0] = 20;
                s[1] = 30;
            }
        }
        assert_eq!(arr.as_slice().unwrap(), &[1, 20, 30, 4, 5]);
    }

    // -----------------------------------------------------------------------
    // 3D indexing
    // -----------------------------------------------------------------------

    #[test]
    fn index_axis_3d() {
        let arr = Array::<i32, Ix3>::from_vec(Ix3::new([2, 3, 4]), (0..24).collect()).unwrap();
        let plane = arr.index_axis(Axis(0), 1).unwrap();
        assert_eq!(plane.shape(), &[3, 4]);
        assert_eq!(*plane.get(&[0, 0]).unwrap(), 12);
    }
}