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
use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;

use super::{types::*, OptionNA, Vector};
use crate::error::Error;
use crate::lang::Signal;
use crate::object::{CowObj, Obj};

/// Subsets
///
/// Representations of how data views might be specified. Indices are 0-indexed,
/// for direct use against rust-internal representations.
///
#[derive(Debug, Clone, PartialEq)]
pub enum Subset {
    Indices(CowObj<Vec<Integer>>),
    Mask(CowObj<Vec<Logical>>),
    Names(CowObj<Vec<Character>>),
    Range(Range<usize>),
}

impl Subset {
    pub fn get_index_at(&self, index: usize) -> Option<usize> {
        match self {
            Subset::Indices(indices) => indices.clone().borrow().get(index).and_then(|i| match i {
                OptionNA::Some(i) => Some((*i as usize).saturating_sub(1)),
                OptionNA::NA => None,
            }),
            Subset::Range(range) => {
                if range.start <= index && index < range.end {
                    Some(range.start + index)
                } else {
                    None
                }
            }
            Subset::Mask(mask) => mask
                .clone()
                .borrow()
                .iter()
                .enumerate()
                .filter_map(|(i, m)| match m {
                    OptionNA::Some(true) => Some(Some(i)),
                    OptionNA::NA => Some(None),
                    _ => None,
                })
                .nth(index)
                .unwrap_or(None),
            Subset::Names(_) => unimplemented!(),
        }
    }

    pub fn len(&self) -> usize {
        match self {
            Subset::Indices(i) => i.len(),
            Subset::Range(r) => r.end - r.start,
            Subset::Mask(_) => usize::MAX,
            Subset::Names(n) => n.len(),
        }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn filter<'a, I>(
        &self,
        mut iter: I,
    ) -> Box<dyn Iterator<Item = (usize, Option<usize>)> + 'a>
    where
        I: Iterator<Item = (usize, Option<usize>)> + 'a,
    {
        match self.clone() {
            Subset::Indices(i) => {
                let l = self.len();

                // fastest case, when no indices are selected
                if l == 0 {
                    Box::new(vec![].into_iter())

                // very fast case, when one index is selected
                } else if l == 1 {
                    let msg = "Expected at least one element to index by";
                    if let OptionNA::Some(to_first) = i.clone().borrow().first().expect(msg) {
                        Box::new(iter.skip(*to_first as usize).take(1))
                    } else {
                        let (i_orig, _) = iter.next().unwrap_or((0, None));
                        Box::new(vec![(i_orig, None)].into_iter())
                    }

                // fast case, when indices are already sorted
                } else if i.borrow().windows(2).all(|w| w[0] <= w[1]) {
                    // when sorted, we can keep our existing iterator and
                    // embed the indices, scanning along the iterator
                    // and yielding indices as they are encountered
                    let ic = i.clone();
                    let ib = ic.borrow().clone();

                    Box::new(
                        iter.enumerate()
                            .scan(
                                (ib, 0),
                                |(indices, i), (xi, (xi_orig, x))| -> Option<Vec<(usize, Option<usize>)>> {
                                    if *i >= indices.len() {
                                        return None;
                                    }

                                    let mut n = 0;
                                    while *i < indices.len()
                                        && indices[*i] == OptionNA::Some(xi as i32)
                                    {
                                        n += 1;
                                        *i += 1;
                                    }

                                    Some(vec![(xi_orig, x); n])
                                },
                            )
                            .flatten(),
                    )
                // worst case, indices in random order
                } else {
                    // enumerate indices and swap so it's (index, enumeration)
                    let ic = i.clone();
                    let ib = ic.borrow();

                    let mut order = ib
                        .iter()
                        .map(|i| match i {
                            OptionNA::NA => -1,
                            OptionNA::Some(i) => *i,
                        })
                        .enumerate()
                        .map(|(i, v)| (v, i)) // cast NAs to -1's
                        .collect::<Vec<_>>();

                    // sort by index to get (sorted indices, order)
                    // we'll use this to sample the existing iterator then
                    // permute it back into the original order
                    order.sort();
                    let (mut i, order): (Vec<_>, Vec<_>) = order.into_iter().unzip();

                    // we'll populate this with the sorted indices first
                    let mut indices: Vec<(usize, Option<usize>)> = vec![(0, None); i.len()];
                    let n_na = i.iter().take_while(|&i| *i == -1).count();

                    // populate non-na elements
                    i.insert(n_na, 0);
                    let diffs = i[n_na..].windows(2).map(|w| w[1] - w[0]);

                    let msg = "exhausted iterator";
                    let (mut i_orig, mut last) = iter.nth(0).expect(msg);
                    for (i, diff) in diffs.enumerate() {
                        if diff > 0 {
                            (i_orig, last) = iter.nth((diff - 1) as usize).expect(msg);
                        }
                        indices[order[i + n_na]] = (i_orig, last);
                    }

                    // and finally we convert our new indices into an iterator
                    Box::new(indices.into_iter())
                }
            }
            Subset::Mask(mask) => {
                Box::new((**mask.borrow()).clone().into_iter().zip(iter).filter_map(
                    |(mask, i @ (i_orig, _))| match mask {
                        OptionNA::Some(true) => Some(i),      // accept index
                        OptionNA::NA => Some((i_orig, None)), // accept, but NA
                        _ => None,                            // filter falses
                    },
                ))
            }
            Subset::Range(range) => Box::new(
                iter.skip(range.start)
                    .enumerate()
                    .take_while(move |(i, _)| i < &(range.end - range.start))
                    .map(|(_, v)| v),
            ),
            Subset::Names(_) => unimplemented!(),
        }
    }
}

impl TryFrom<Obj> for Subset {
    type Error = Signal;
    fn try_from(value: Obj) -> Result<Self, Self::Error> {
        let err = Error::Other("Cannot use object for indexing".to_string());
        match value {
            Obj::Vector(v) => Subset::try_from(v),
            _ => err.into(),
        }
    }
}

impl From<usize> for Subset {
    fn from(value: usize) -> Self {
        Subset::Indices(vec![OptionNA::Some(value as i32)].into())
    }
}

impl From<Range<usize>> for Subset {
    fn from(value: Range<usize>) -> Self {
        Subset::Range(value)
    }
}

impl From<Vec<usize>> for Subset {
    fn from(value: Vec<usize>) -> Self {
        Subset::Indices(CowObj::new(Rc::new(RefCell::new(Rc::new(
            value
                .iter()
                .map(|i| OptionNA::Some(*i as i32))
                .collect::<Vec<_>>(),
        )))))
    }
}

impl TryFrom<Vector> for Subset {
    type Error = Signal;
    fn try_from(value: Vector) -> Result<Self, Self::Error> {
        match value {
            value @ Vector::Double(_) => Subset::try_from(value.as_integer()),
            Vector::Integer(v) => {
                let y = v
                    .iter_values()
                    .map(|i| match i {
                        OptionNA::Some(x) => OptionNA::Some(x - 1),
                        OptionNA::NA => OptionNA::NA,
                    })
                    .collect();

                Ok(Subset::Indices(CowObj::new(Rc::new(RefCell::new(
                    Rc::new(y),
                )))))
            }
            Vector::Logical(v) => {
                let all_false = v
                    .inner()
                    .clone()
                    .borrow()
                    .iter()
                    .all(|i| i == &OptionNA::Some(false));

                // special case when all are false, treat it as no indices
                if all_false {
                    Ok(Subset::Indices(Vec::new().into()))
                } else {
                    Ok(Subset::Mask(v.inner()))
                }
            }
            Vector::Character(v) => Ok(Subset::Names(v.inner())),
        }
    }
}