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
use crate::{
    core::prelude::*,
    errors::prelude::*,
    extensions::prelude::*,
    validators::prelude::*,
};

/// ArrayTrait - Array Split functions
pub trait ArraySplit<T: ArrayElement> where Self: Sized + Clone {

    /// Split an array into multiple sub-arrays
    ///
    /// # Arguments
    ///
    /// * `parts` - indices defining how to split the array
    /// * `axis` - the axis along which to split. optional, defaults to 0
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 7);
    /// let split = arr.array_split(3, None).unwrap();
    /// assert_eq!(vec![array_flat!(i32, 0, 1, 2).unwrap(), array_flat!(i32, 3, 4, 5).unwrap(), array_flat!(i32, 6, 7).unwrap()], split);
    ///
    /// let arr = array_arange!(i32, 0, 8);
    /// let split = arr.array_split(4, None).unwrap();
    /// assert_eq!(vec![array_flat!(i32, 0, 1, 2).unwrap(), array_flat!(i32, 3, 4).unwrap(), array_flat!(i32, 5, 6).unwrap(), array_flat!(i32, 7, 8).unwrap()], split);
    /// ```
    fn array_split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError>;

    /// Split an array into multiple sub-arrays of equal size
    ///
    /// # Arguments
    ///
    /// * `parts` - indices defining how to split the array
    /// * `axis` - the axis along which to split. optional, defaults to 0
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 8);
    /// let split = arr.split(3, None).unwrap();
    /// assert_eq!(vec![array_flat!(i32, 0, 1, 2).unwrap(), array_flat!(i32, 3, 4, 5).unwrap(), array_flat!(i32, 6, 7, 8).unwrap()], split);
    ///
    /// let arr = array_arange!(i32, 0, 7);
    /// let split = arr.split(4, None).unwrap();
    /// assert_eq!(vec![array_flat!(i32, 0, 1).unwrap(), array_flat!(i32, 2, 3).unwrap(), array_flat!(i32, 4, 5).unwrap(), array_flat!(i32, 6, 7).unwrap()], split);
    /// ```
    fn split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError>;

    /// Split an array into multiple sub-arrays of equal size by axis
    ///
    /// # Arguments
    ///
    /// * `axis` - the axis along which to split
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 3).reshape(&[2, 2]);
    /// let split = arr.split_axis(0).unwrap();
    /// assert_eq!(vec![array!(i32, [[0, 1]]).unwrap(), array!(i32, [[2, 3]]).unwrap()], split);
    ///
    /// let arr = array_arange!(i32, 0, 7).reshape(&[2, 2, 2]);
    /// let split = arr.split_axis(1).unwrap();
    /// assert_eq!(vec![array!(i32, [[[0, 1]], [[4, 5]]]).unwrap(), array!(i32, [[[2, 3]], [[6, 7]]]).unwrap()], split);
    /// ```
    fn split_axis(&self, axis: usize) -> Result<Vec<Array<T>>, ArrayError>;

    /// Split an array into multiple sub-arrays horizontally (column-wise)
    ///
    /// # Arguments
    ///
    /// * `parts` - indices defining how to split the array
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 7).reshape(&[2, 2, 2]).unwrap();
    /// let split = arr.hsplit(2).unwrap();
    /// assert_eq!(vec![array!(i32, [[[0, 1]], [[4, 5]]]).unwrap(), array!(i32, [[[2, 3]], [[6, 7]]]).unwrap()], split);
    /// ```
    fn hsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError>;

    /// Split an array into multiple sub-arrays vertically (row-wise)
    ///
    /// # Arguments
    ///
    /// * `parts` - indices defining how to split the array
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 7).reshape(&[2, 2, 2]).unwrap();
    /// let split = arr.vsplit(2).unwrap();
    /// assert_eq!(vec![array!(i32, [[[0, 1], [2, 3]]]).unwrap(), array!(i32, [[[4, 5], [6, 7]]]).unwrap()], split);
    /// ```
    fn vsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError>;

    /// Split an array into multiple sub-arrays along the 3rd axis (depth)
    ///
    /// # Arguments
    ///
    /// * `parts` - indices defining how to split the array
    ///
    /// # Examples
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = array_arange!(i32, 0, 7).reshape(&[2, 2, 2]).unwrap();
    /// let split = arr.dsplit(2).unwrap();
    /// assert_eq!(vec![array!(i32, [[[0], [2]], [[4], [6]]]).unwrap(), array!(i32, [[[1], [3]], [[5], [7]]]).unwrap()], split);
    /// ```
    fn dsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError>;
}

impl <T: ArrayElement> ArraySplit<T> for Array<T> {

    fn array_split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError> {
        if parts == 0 { return Err(ArrayError::ParameterError { param: "parts", message: "number of sections must be larger than 0", }) }
        self.axis_opt_in_bounds(axis)?;
        if self.is_empty()? { return Ok(vec![self.clone()]) }

        let axis = axis.unwrap_or(0);
        let n_total = self.len()?;

        let (sections, extras) = (n_total / parts, n_total % parts);
        let section_sizes = std::iter::repeat(sections + 1)
            .take(extras)
            .chain(std::iter::repeat(sections).take(parts - extras))
            .collect::<Vec<usize>>()
            .insert_at(0, 0);
        let mut div_points = vec![0; section_sizes.len()];
        (0 .. div_points.len()).for_each(|i| {
            div_points[i] = section_sizes.clone()[0 ..= i]
                .iter_mut()
                .fold(0, |acc, x| { *x += acc; *x });
        });

        let arr = self.rollaxis(axis as isize, None);
        if let Ok(arr) = arr {
            let result = div_points
                .windows(2)
                .map(|w| arr.clone().into_iter()
                    .skip(w[0]).take(w[1] - w[0])
                    .collect::<Self>())
                .map(|m| {
                    if self.ndim()? == 1 { Ok(m) }
                    else {
                        let mut new_shape = self.get_shape()?;
                        new_shape[axis] /= parts;
                        m.reshape(&new_shape)
                    }
                })
                .collect::<Vec<Result<Self, _>>>();
            if let Err(err) = result.has_error() { Err(err) }
            else { Ok(result.into_iter().map(|a| a.unwrap()).collect()) }
        } else {
            Err(arr.err().unwrap())
        }
    }

    fn split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError> {
        self.axis_opt_in_bounds(axis)?;
        if parts == 0 {
            Err(ArrayError::ParameterError { param: "parts", message: "number of sections must be larger than 0", })
        } else {
            if self.is_empty()? { return Ok(vec![self.clone()]) }
            let n_total = self.shape[axis.unwrap_or(0)];

            if n_total % parts != 0 { Err(ArrayError::ParameterError { param: "parts", message: "array split does not result in an equal division", }) }
            else { self.array_split(parts, axis) }
        }
    }

    fn split_axis(&self, axis: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.axis_in_bounds(axis)?;
        if self.is_empty()? || self.ndim()? == 1 { Ok(vec![self.clone()]) }
        else { self.array_split(self.shape[axis], Some(axis)) }
    }

    fn hsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.is_dim_unsupported(&[0])?;
        if parts == 0 {
            Err(ArrayError::ParameterError { param: "parts", message: "number of sections must be larger than 0", })
        } else {
            match self.ndim()? {
                1 => self.split(parts, Some(0)),
                _ => self.split(parts, Some(1)),
            }
        }
    }

    fn vsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.is_dim_unsupported(&[0, 1])?;
        if parts == 0 {
            Err(ArrayError::ParameterError { param: "parts", message: "number of sections must be larger than 0", })
        } else {
            self.split(parts, Some(0))
        }
    }

    fn dsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.is_dim_unsupported(&[0, 1, 2])?;
        if parts == 0 {
            Err(ArrayError::ParameterError { param: "parts", message: "number of sections must be larger than 0", })
        } else {
            self.split(parts, Some(2))
        }
    }
}

impl <T: ArrayElement> ArraySplit<T> for Result<Array<T>, ArrayError> {

    fn array_split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.array_split(parts, axis)
    }

    fn split(&self, parts: usize, axis: Option<usize>) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.split(parts, axis)
    }

    fn split_axis(&self, axis: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.split_axis(axis)
    }

    fn hsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.hsplit(parts)
    }

    fn vsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.vsplit(parts)
    }

    fn dsplit(&self, parts: usize) -> Result<Vec<Array<T>>, ArrayError> {
        self.clone()?.dsplit(parts)
    }
}