concision_core/ops/
reshape.rs

1/*
2    Appellation: reshape <module>
3    Contrib: @FL03
4*/
5use ndarray::{ArrayBase, Axis, Dimension, RawData, RawDataClone, RemoveAxis};
6
7/// The [`DecrementAxis`] trait defines a method enabling an axis to decrement itself,
8pub trait DecrementAxis {
9    type Output;
10
11    fn dec(&self) -> Self::Output;
12}
13/// The [`IncrementAxis`] trait defines a method enabling an axis to increment itself,
14/// effectively adding a new axis to the array.
15pub trait IncrementAxis {
16    type Output;
17
18    fn inc(&self) -> Self::Output;
19}
20/// The [`Unsqueeze`] trait establishes an interface for a routine that _unsqueezes_ an array,
21/// by inserting a new axis at a specified position. This is useful for reshaping arrays to
22/// meet specific dimensional requirements.
23pub trait Unsqueeze {
24    type Output;
25
26    fn unsqueeze(self, axis: usize) -> Self::Output;
27}
28/*
29 ************* Implementations *************
30*/
31impl<D> DecrementAxis for D
32where
33    D: RemoveAxis,
34{
35    type Output = D::Smaller;
36
37    fn dec(&self) -> Self::Output {
38        self.remove_axis(Axis(self.ndim() - 1))
39    }
40}
41
42impl<A, S, D> Unsqueeze for ArrayBase<S, D>
43where
44    D: Dimension,
45    S: RawData<Elem = A>,
46{
47    type Output = ArrayBase<S, D::Larger>;
48
49    fn unsqueeze(self, axis: usize) -> Self::Output {
50        self.insert_axis(Axis(axis))
51    }
52}
53
54impl<A, S, D> Unsqueeze for &ArrayBase<S, D>
55where
56    D: Dimension,
57    S: RawDataClone<Elem = A>,
58{
59    type Output = ArrayBase<S, D::Larger>;
60
61    fn unsqueeze(self, axis: usize) -> Self::Output {
62        self.clone().insert_axis(Axis(axis))
63    }
64}