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
use crate::prelude::*;
use crate::{datatypes::PlHashMap, use_string_cache};
use arrow::array::*;
pub enum RevMappingBuilder {
Global(PlHashMap<u32, u32>, MutableUtf8Array<i64>, u128),
Local(MutableUtf8Array<i64>),
}
impl RevMappingBuilder {
fn insert(&mut self, idx: u32, value: &str) {
use RevMappingBuilder::*;
match self {
Local(builder) => builder.push(Some(value)),
Global(map, builder, _) => {
if !map.contains_key(&idx) {
builder.push(Some(value));
let new_idx = builder.len() as u32 - 1;
map.insert(idx, new_idx);
}
}
};
}
fn finish(self) -> RevMapping {
use RevMappingBuilder::*;
match self {
Local(b) => RevMapping::Local(b.into()),
Global(mut map, b, uuid) => {
map.shrink_to_fit();
RevMapping::Global(map, b.into(), uuid)
}
}
}
}
#[derive(Debug)]
pub enum RevMapping {
Global(PlHashMap<u32, u32>, Utf8Array<i64>, u128),
Local(Utf8Array<i64>),
}
impl Default for RevMapping {
fn default() -> Self {
let slice: &[Option<&str>] = &[];
RevMapping::Local(Utf8Array::<i64>::from(slice))
}
}
#[allow(clippy::len_without_is_empty)]
impl RevMapping {
pub fn len(&self) -> usize {
match self {
Self::Global(_, a, _) => a.len(),
Self::Local(a) => a.len(),
}
}
pub fn get(&self, idx: u32) -> &str {
match self {
Self::Global(map, a, _) => {
let idx = *map.get(&idx).unwrap();
a.value(idx as usize)
}
Self::Local(a) => a.value(idx as usize),
}
}
pub(crate) unsafe fn get_unchecked(&self, idx: u32) -> &str {
match self {
Self::Global(map, a, _) => {
let idx = *map.get(&idx).unwrap();
a.value_unchecked(idx as usize)
}
Self::Local(a) => a.value_unchecked(idx as usize),
}
}
pub fn same_src(&self, other: &Self) -> bool {
match (self, other) {
(RevMapping::Global(_, _, l), RevMapping::Global(_, _, r)) => *l == *r,
_ => false,
}
}
pub fn find(&self, value: &str) -> Option<u32> {
match self {
Self::Global(map, a, _) => {
map.iter()
.find(|(_k, &v)| (unsafe { a.value_unchecked(v as usize) } == value))
.map(|(k, _v)| *k)
}
Self::Local(a) => {
unsafe { (0..a.len()).find(|idx| a.value_unchecked(*idx) == value) }
.map(|idx| idx as u32)
}
}
}
}
pub struct CategoricalChunkedBuilder {
array_builder: UInt32Vec,
name: String,
reverse_mapping: RevMappingBuilder,
}
impl CategoricalChunkedBuilder {
pub fn new(name: &str, capacity: usize) -> Self {
let builder = MutableUtf8Array::<i64>::with_capacity(capacity / 10);
let reverse_mapping = if use_string_cache() {
let uuid = crate::STRING_CACHE.lock_map().uuid;
RevMappingBuilder::Global(PlHashMap::default(), builder, uuid)
} else {
RevMappingBuilder::Local(builder)
};
Self {
array_builder: UInt32Vec::with_capacity(capacity),
name: name.to_string(),
reverse_mapping,
}
}
}
impl CategoricalChunkedBuilder {
pub fn drain_iter<'a, I>(&mut self, i: I)
where
I: IntoIterator<Item = Option<&'a str>>,
{
if use_string_cache() {
let mut cache = crate::STRING_CACHE.lock_map();
for opt_s in i {
match opt_s {
Some(s) => {
let idx = match cache.map.get(s) {
Some(idx) => *idx,
None => {
let idx = cache.map.len() as u32;
cache.map.insert(s.to_string(), idx);
idx
}
};
self.reverse_mapping.insert(idx, s);
self.array_builder.push(Some(idx));
}
None => {
self.array_builder.push(None);
}
}
}
} else {
let mut mapping = PlHashMap::new();
for opt_s in i {
match opt_s {
Some(s) => {
let idx = match mapping.get(s) {
Some(idx) => *idx,
None => {
let idx = mapping.len() as u32;
self.reverse_mapping.insert(idx, s);
mapping.insert(s, idx);
idx
}
};
self.array_builder.push(Some(idx));
}
None => {
self.array_builder.push(None);
}
}
}
if mapping.len() > u32::MAX as usize {
panic!("not more than {} categories supported", u32::MAX)
};
}
}
pub fn finish(self) -> CategoricalChunked {
CategoricalChunked::from_chunks_original(
&self.name,
vec![self.array_builder.into_arc()],
self.reverse_mapping.finish(),
)
}
}
#[cfg(test)]
mod test {
use crate::chunked_array::categorical::CategoricalChunkedBuilder;
use crate::prelude::*;
use crate::{reset_string_cache, toggle_string_cache, SINGLE_LOCK};
#[test]
fn test_categorical_rev() -> Result<()> {
let _lock = SINGLE_LOCK.lock();
reset_string_cache();
let slice = &[
Some("foo"),
None,
Some("bar"),
Some("foo"),
Some("foo"),
Some("bar"),
];
let ca = Utf8Chunked::new("a", slice);
let out = ca.cast(&DataType::Categorical(None))?;
let out = out.categorical().unwrap().clone();
assert_eq!(out.get_rev_map().len(), 2);
toggle_string_cache(true);
let out = ca.cast(&DataType::Categorical(None))?;
let out = out.categorical().unwrap().clone();
assert_eq!(out.get_rev_map().len(), 2);
let out = ca.cast(&DataType::Categorical(None))?;
let out = out.categorical().unwrap().clone();
assert_eq!(out.get_rev_map().len(), 2);
let ca1 = Utf8Chunked::new("a", slice).cast(&DataType::Categorical(None))?;
let mut ca1 = ca1.categorical().unwrap().clone();
let ca2 = Utf8Chunked::new("a", slice).cast(&DataType::Categorical(None))?;
let ca2 = ca2.categorical().unwrap();
ca1.append(ca2).unwrap();
Ok(())
}
#[test]
fn test_categorical_builder() {
use crate::{reset_string_cache, toggle_string_cache};
let _lock = crate::SINGLE_LOCK.lock();
for b in &[false, true] {
reset_string_cache();
toggle_string_cache(*b);
let mut builder1 = CategoricalChunkedBuilder::new("foo", 10);
let mut builder2 = CategoricalChunkedBuilder::new("foo", 10);
builder1.drain_iter(vec![None, Some("hello"), Some("vietnam")]);
builder2.drain_iter(vec![Some("hello"), None, Some("world")].into_iter());
let s = builder1.finish().into_series();
assert_eq!(s.str_value(0), "null");
assert_eq!(s.str_value(1), "hello");
assert_eq!(s.str_value(2), "vietnam");
let s = builder2.finish().into_series();
assert_eq!(s.str_value(0), "hello");
assert_eq!(s.str_value(1), "null");
assert_eq!(s.str_value(2), "world");
}
}
}