ndarray/dimension/
reshape.rs

1use crate::dimension::sequence::{Forward, Reverse, Sequence, SequenceMut};
2use crate::{Dimension, ErrorKind, Order, ShapeError};
3
4#[inline]
5pub(crate) fn reshape_dim<D, E>(from: &D, strides: &D, to: &E, order: Order) -> Result<E, ShapeError>
6where
7    D: Dimension,
8    E: Dimension,
9{
10    debug_assert_eq!(from.ndim(), strides.ndim());
11    let mut to_strides = E::zeros(to.ndim());
12    match order {
13        Order::RowMajor => {
14            reshape_dim_c(&Forward(from), &Forward(strides), &Forward(to), Forward(&mut to_strides))?;
15        }
16        Order::ColumnMajor => {
17            reshape_dim_c(&Reverse(from), &Reverse(strides), &Reverse(to), Reverse(&mut to_strides))?;
18        }
19    }
20    Ok(to_strides)
21}
22
23/// Try to reshape an array with dimensions `from_dim` and strides `from_strides` to the new
24/// dimension `to_dim`, while keeping the same layout of elements in memory. The strides needed
25/// if this is possible are stored into `to_strides`.
26///
27/// This function uses RowMajor index ordering if the inputs are read in the forward direction
28/// (index 0 is axis 0 etc) and ColumnMajor index ordering if the inputs are read in reversed
29/// direction (as made possible with the Sequence trait).
30///
31/// Preconditions:
32///
33/// 1. from_dim and to_dim are valid dimensions (product of all non-zero axes
34///    fits in isize::MAX).
35/// 2. from_dim and to_dim are don't have any axes that are zero (that should be handled before
36///    this function).
37/// 3. `to_strides` should be an all-zeros or all-ones dimension of the right dimensionality
38///    (but it will be overwritten after successful exit of this function).
39///
40/// This function returns:
41///
42/// - IncompatibleShape if the two shapes are not of matching number of elements
43/// - IncompatibleLayout if the input shape and stride can not be remapped to the output shape
44///   without moving the array data into a new memory layout.
45/// - Ok if the from dim could be mapped to the new to dim.
46fn reshape_dim_c<D, E, E2>(from_dim: &D, from_strides: &D, to_dim: &E, mut to_strides: E2) -> Result<(), ShapeError>
47where
48    D: Sequence<Output = usize>,
49    E: Sequence<Output = usize>,
50    E2: SequenceMut<Output = usize>,
51{
52    // cursor indexes into the from and to dimensions
53    let mut fi = 0; // index into `from_dim`
54    let mut ti = 0; // index into `to_dim`.
55
56    while fi < from_dim.len() && ti < to_dim.len() {
57        let mut fd = from_dim[fi];
58        let mut fs = from_strides[fi] as isize;
59        let mut td = to_dim[ti];
60
61        if fd == td {
62            to_strides[ti] = from_strides[fi];
63            fi += 1;
64            ti += 1;
65            continue;
66        }
67
68        if fd == 1 {
69            fi += 1;
70            continue;
71        }
72
73        if td == 1 {
74            to_strides[ti] = 1;
75            ti += 1;
76            continue;
77        }
78
79        if fd == 0 || td == 0 {
80            debug_assert!(false, "zero dim not handled by this function");
81            return Err(ShapeError::from_kind(ErrorKind::IncompatibleShape));
82        }
83
84        // stride times element count is to be distributed out over a combination of axes.
85        let mut fstride_whole = fs * (fd as isize);
86        let mut fd_product = fd; // cumulative product of axis lengths in the combination (from)
87        let mut td_product = td; // cumulative product of axis lengths in the combination (to)
88
89        // The two axis lengths are not a match, so try to combine multiple axes
90        // to get it to match up.
91        while fd_product != td_product {
92            if fd_product < td_product {
93                // Take another axis on the from side
94                fi += 1;
95                if fi >= from_dim.len() {
96                    return Err(ShapeError::from_kind(ErrorKind::IncompatibleShape));
97                }
98                fd = from_dim[fi];
99                fd_product *= fd;
100                if fd > 1 {
101                    let fs_old = fs;
102                    fs = from_strides[fi] as isize;
103                    // check if this axis and the next are contiguous together
104                    if fs_old != fd as isize * fs {
105                        return Err(ShapeError::from_kind(ErrorKind::IncompatibleLayout));
106                    }
107                }
108            } else {
109                // Take another axis on the `to` side
110                // First assign the stride to the axis we leave behind
111                fstride_whole /= td as isize;
112                to_strides[ti] = fstride_whole as usize;
113                ti += 1;
114                if ti >= to_dim.len() {
115                    return Err(ShapeError::from_kind(ErrorKind::IncompatibleShape));
116                }
117
118                td = to_dim[ti];
119                td_product *= td;
120            }
121        }
122
123        fstride_whole /= td as isize;
124        to_strides[ti] = fstride_whole as usize;
125
126        fi += 1;
127        ti += 1;
128    }
129
130    // skip past 1-dims at the end
131    while fi < from_dim.len() && from_dim[fi] == 1 {
132        fi += 1;
133    }
134
135    while ti < to_dim.len() && to_dim[ti] == 1 {
136        to_strides[ti] = 1;
137        ti += 1;
138    }
139
140    if fi < from_dim.len() || ti < to_dim.len() {
141        return Err(ShapeError::from_kind(ErrorKind::IncompatibleShape));
142    }
143
144    Ok(())
145}
146
147#[cfg(feature = "std")]
148#[test]
149fn test_reshape()
150{
151    use crate::Dim;
152
153    macro_rules! test_reshape {
154        (fail $order:ident from $from:expr, $stride:expr, to $to:expr) => {
155            let res = reshape_dim(&Dim($from), &Dim($stride), &Dim($to), Order::$order);
156            println!("Reshape {:?} {:?} to {:?}, order {:?}\n  => {:?}",
157                     $from, $stride, $to, Order::$order, res);
158            let _res = res.expect_err("Expected failed reshape");
159        };
160        (ok $order:ident from $from:expr, $stride:expr, to $to:expr, $to_stride:expr) => {{
161            let res = reshape_dim(&Dim($from), &Dim($stride), &Dim($to), Order::$order);
162            println!("Reshape {:?} {:?} to {:?}, order {:?}\n  => {:?}",
163                     $from, $stride, $to, Order::$order, res);
164            println!("default stride for from dim: {:?}", Dim($from).default_strides());
165            println!("default stride for to dim: {:?}", Dim($to).default_strides());
166            let res = res.expect("Expected successful reshape");
167            assert_eq!(res, Dim($to_stride), "mismatch in strides");
168        }};
169    }
170
171    test_reshape!(ok C from [1, 2, 3], [6, 3, 1], to [1, 2, 3], [6, 3, 1]);
172    test_reshape!(ok C from [1, 2, 3], [6, 3, 1], to [2, 3], [3, 1]);
173    test_reshape!(ok C from [1, 2, 3], [6, 3, 1], to [6], [1]);
174    test_reshape!(fail C from [1, 2, 3], [6, 3, 1], to [1]);
175    test_reshape!(fail F from [1, 2, 3], [6, 3, 1], to [1]);
176
177    test_reshape!(ok C from [6], [1], to [3, 2], [2, 1]);
178    test_reshape!(ok C from [3, 4, 5], [20, 5, 1], to [4, 15], [15, 1]);
179
180    test_reshape!(ok C from [4, 4, 4], [16, 4, 1], to [16, 4], [4, 1]);
181
182    test_reshape!(ok C from [4, 4], [4, 1], to [2, 2, 4, 1], [8, 4, 1, 1]);
183    test_reshape!(ok C from [4, 4], [4, 1], to [2, 2, 4], [8, 4, 1]);
184    test_reshape!(ok C from [4, 4], [4, 1], to [2, 2, 2, 2], [8, 4, 2, 1]);
185
186    test_reshape!(ok C from [4, 4], [4, 1], to [2, 2, 1, 4], [8, 4, 1, 1]);
187
188    test_reshape!(ok C from [4, 4, 4], [16, 4, 1], to [16, 4], [4, 1]);
189    test_reshape!(ok C from [3, 4, 4], [16, 4, 1], to [3, 16], [16, 1]);
190
191    test_reshape!(ok C from [4, 4], [8, 1], to [2, 2, 2, 2], [16, 8, 2, 1]);
192
193    test_reshape!(fail C from [4, 4], [8, 1], to [2, 1, 4, 2]);
194
195    test_reshape!(ok C from [16], [4], to [2, 2, 4], [32, 16, 4]);
196    test_reshape!(ok C from [16], [-4isize as usize], to [2, 2, 4],
197                  [-32isize as usize, -16isize as usize, -4isize as usize]);
198    test_reshape!(ok F from [16], [4], to [2, 2, 4], [4, 8, 16]);
199    test_reshape!(ok F from [16], [-4isize as usize], to [2, 2, 4],
200                  [-4isize as usize, -8isize as usize, -16isize as usize]);
201
202    test_reshape!(ok C from [3, 4, 5], [20, 5, 1], to [12, 5], [5, 1]);
203    test_reshape!(ok C from [3, 4, 5], [20, 5, 1], to [4, 15], [15, 1]);
204    test_reshape!(fail F from [3, 4, 5], [20, 5, 1], to [4, 15]);
205    test_reshape!(ok C from [3, 4, 5, 7], [140, 35, 7, 1], to [28, 15], [15, 1]);
206
207    // preserve stride if shape matches
208    test_reshape!(ok C from [10], [2], to [10], [2]);
209    test_reshape!(ok F from [10], [2], to [10], [2]);
210    test_reshape!(ok C from [2, 10], [1, 2], to [2, 10], [1, 2]);
211    test_reshape!(ok F from [2, 10], [1, 2], to [2, 10], [1, 2]);
212    test_reshape!(ok C from [3, 4, 5], [20, 5, 1], to [3, 4, 5], [20, 5, 1]);
213    test_reshape!(ok F from [3, 4, 5], [20, 5, 1], to [3, 4, 5], [20, 5, 1]);
214
215    test_reshape!(ok C from [3, 4, 5], [4, 1, 1], to [12, 5], [1, 1]);
216    test_reshape!(ok F from [3, 4, 5], [1, 3, 12], to [12, 5], [1, 12]);
217    test_reshape!(ok F from [3, 4, 5], [1, 3, 1], to [12, 5], [1, 1]);
218
219    // broadcast shapes
220    test_reshape!(ok C from [3, 4, 5, 7], [0, 0, 7, 1], to [12, 35], [0, 1]);
221    test_reshape!(fail C from [3, 4, 5, 7], [0, 0, 7, 1], to [28, 15]);
222
223    // one-filled shapes
224    test_reshape!(ok C from [10], [1], to [1, 10, 1, 1, 1], [1, 1, 1, 1, 1]);
225    test_reshape!(ok F from [10], [1], to [1, 10, 1, 1, 1], [1, 1, 1, 1, 1]);
226    test_reshape!(ok C from [1, 10], [10, 1], to [1, 10, 1, 1, 1], [10, 1, 1, 1, 1]);
227    test_reshape!(ok F from [1, 10], [10, 1], to [1, 10, 1, 1, 1], [10, 1, 1, 1, 1]);
228    test_reshape!(ok C from [1, 10], [1, 1], to [1, 5, 1, 1, 2], [1, 2, 2, 2, 1]);
229    test_reshape!(ok F from [1, 10], [1, 1], to [1, 5, 1, 1, 2], [1, 1, 5, 5, 5]);
230    test_reshape!(ok C from [10, 1, 1, 1, 1], [1, 1, 1, 1, 1], to [10], [1]);
231    test_reshape!(ok F from [10, 1, 1, 1, 1], [1, 1, 1, 1, 1], to [10], [1]);
232    test_reshape!(ok C from [1, 5, 1, 2, 1], [1, 2, 1, 1, 1], to [10], [1]);
233    test_reshape!(fail F from [1, 5, 1, 2, 1], [1, 2, 1, 1, 1], to [10]);
234    test_reshape!(ok F from [1, 5, 1, 2, 1], [1, 1, 1, 5, 1], to [10], [1]);
235    test_reshape!(fail C from [1, 5, 1, 2, 1], [1, 1, 1, 5, 1], to [10]);
236}