-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathinteger.rs
More file actions
286 lines (244 loc) · 10.3 KB
/
integer.rs
File metadata and controls
286 lines (244 loc) · 10.3 KB
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
279
280
281
282
283
284
285
286
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
//! Integer-specific dictionary encoding implementation.
//!
//! Vortex encoders must always produce unsigned integer codes; signed codes are only accepted
//! for external compatibility.
use vortex_array::ArrayRef;
use vortex_array::Canonical;
use vortex_array::IntoArray;
use vortex_array::arrays::DictArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::dict::DictArrayExt;
use vortex_array::arrays::primitive::PrimitiveArrayExt;
use vortex_array::validity::Validity;
use vortex_buffer::Buffer;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use crate::CascadingCompressor;
use crate::builtins::IntDictScheme;
use crate::builtins::is_integer_primitive;
use crate::ctx::CompressorContext;
use crate::estimate::CompressionEstimate;
use crate::scheme::Scheme;
use crate::scheme::SchemeExt;
use crate::stats::ArrayAndStats;
use crate::stats::GenerateStatsOptions;
use crate::stats::IntegerErasedStats;
use crate::stats::IntegerStats;
impl Scheme for IntDictScheme {
fn scheme_name(&self) -> &'static str {
"vortex.int.dict"
}
fn matches(&self, canonical: &Canonical) -> bool {
is_integer_primitive(canonical)
}
fn stats_options(&self) -> GenerateStatsOptions {
GenerateStatsOptions {
count_distinct_values: true,
}
}
/// Children: values=0, codes=1.
fn num_children(&self) -> usize {
2
}
fn expected_compression_ratio(
&self,
data: &mut ArrayAndStats,
_ctx: CompressorContext,
) -> CompressionEstimate {
let bit_width = data.array_as_primitive().ptype().bit_width();
let stats = data.integer_stats();
if stats.value_count() == 0 {
return CompressionEstimate::Skip;
}
let distinct_values_count = stats.distinct_count().vortex_expect(
"this must be present since `DictScheme` declared that we need distinct values",
);
// If > 50% of the values are distinct, skip dictionary scheme.
if distinct_values_count > stats.value_count() / 2 {
return CompressionEstimate::Skip;
}
// Ignore nulls encoding for the estimate. We only focus on values.
let values_size = bit_width * distinct_values_count as usize;
// TODO(connor): Should we just hardcode this instead of let the compressor choose?
// Assume codes are compressed RLE + BitPacking.
let codes_bw = u32::BITS - distinct_values_count.leading_zeros();
let n_runs = (stats.value_count() / stats.average_run_length()) as usize;
// Assume that codes will either be BitPack or RLE-BitPack.
let codes_size_bp = codes_bw as usize * stats.value_count() as usize;
let codes_size_rle_bp = usize::checked_mul(codes_bw as usize + 32, n_runs);
let codes_size = usize::min(codes_size_bp, codes_size_rle_bp.unwrap_or(usize::MAX));
let before = stats.value_count() as usize * bit_width;
CompressionEstimate::Ratio(before as f64 / (values_size + codes_size) as f64)
}
fn compress(
&self,
compressor: &CascadingCompressor,
data: &mut ArrayAndStats,
ctx: CompressorContext,
) -> VortexResult<ArrayRef> {
// TODO(connor): Fight the borrow checker (needs interior mutability)!
let stats = data.integer_stats().clone();
// If there are no non-null values (e.g., an all-null sample), there are no distinct
// values to dictionary-encode. Return the array unchanged.
if stats.value_count() == 0 {
return Ok(data.array().clone());
}
let dict = dictionary_encode(data.array_as_primitive(), &stats)?;
// Values = child 0.
let compressed_values = compressor.compress_child(dict.values(), &ctx, self.id(), 0)?;
// Codes = child 1.
let narrowed_codes = dict
.codes()
.clone()
.execute::<PrimitiveArray>(&mut compressor.execution_ctx())?
.narrow()?
.into_array();
let compressed_codes = compressor.compress_child(&narrowed_codes, &ctx, self.id(), 1)?;
// SAFETY: compressing codes does not change their values.
unsafe {
Ok(
DictArray::new_unchecked(compressed_codes, compressed_values)
.set_all_values_referenced(dict.has_all_values_referenced())
.into_array(),
)
}
}
}
/// Encodes a typed integer array into a [`DictArray`] using the pre-computed distinct values.
macro_rules! typed_encode {
($source_array:ident, $stats:ident, $typed:ident, $typ:ty) => {{
let distinct = $typed.distinct().vortex_expect(
"this must be present since `DictScheme` declared that we need distinct values",
);
let values_validity = match $source_array.validity()? {
Validity::NonNullable => Validity::NonNullable,
_ => Validity::AllValid,
};
let codes_validity = $source_array.validity()?;
let values: Buffer<$typ> = distinct.distinct_values().keys().map(|x| x.0).collect();
let max_code = values.len();
let codes = if max_code <= u8::MAX as usize {
let buf = <DictEncoder as Encode<$typ, u8>>::encode(
&values,
$source_array.as_slice::<$typ>(),
);
PrimitiveArray::new(buf, codes_validity).into_array()
} else if max_code <= u16::MAX as usize {
let buf = <DictEncoder as Encode<$typ, u16>>::encode(
&values,
$source_array.as_slice::<$typ>(),
);
PrimitiveArray::new(buf, codes_validity).into_array()
} else {
let buf = <DictEncoder as Encode<$typ, u32>>::encode(
&values,
$source_array.as_slice::<$typ>(),
);
PrimitiveArray::new(buf, codes_validity).into_array()
};
let values = PrimitiveArray::new(values, values_validity).into_array();
// SAFETY: invariants enforced in DictEncoder.
Ok(unsafe { DictArray::new_unchecked(codes, values).set_all_values_referenced(true) })
}};
}
/// Compresses an integer array into a dictionary array according to attached stats.
///
/// # Errors
///
/// Returns an error if unable to compute validity.
#[expect(
clippy::cognitive_complexity,
reason = "complexity from match on all integer types"
)]
pub fn dictionary_encode(array: PrimitiveArray, stats: &IntegerStats) -> VortexResult<DictArray> {
match stats.erased() {
IntegerErasedStats::U8(typed) => typed_encode!(array, stats, typed, u8),
IntegerErasedStats::U16(typed) => typed_encode!(array, stats, typed, u16),
IntegerErasedStats::U32(typed) => typed_encode!(array, stats, typed, u32),
IntegerErasedStats::U64(typed) => typed_encode!(array, stats, typed, u64),
IntegerErasedStats::I8(typed) => typed_encode!(array, stats, typed, i8),
IntegerErasedStats::I16(typed) => typed_encode!(array, stats, typed, i16),
IntegerErasedStats::I32(typed) => typed_encode!(array, stats, typed, i32),
IntegerErasedStats::I64(typed) => typed_encode!(array, stats, typed, i64),
}
}
/// Stateless encoder that maps values to dictionary codes via a `HashMap`.
struct DictEncoder;
/// Trait for encoding values of type `T` into codes of type `I`.
trait Encode<T, I> {
/// Using the distinct value set, turn the values into a set of codes.
fn encode(distinct: &[T], values: &[T]) -> Buffer<I>;
}
/// Implements [`Encode`] for an integer type with all code width variants (u8, u16, u32).
macro_rules! impl_encode {
($typ:ty) => { impl_encode!($typ, u8, u16, u32); };
($typ:ty, $($ityp:ty),+) => {
$(
impl Encode<$typ, $ityp> for DictEncoder {
#[allow(clippy::cast_possible_truncation)]
fn encode(distinct: &[$typ], values: &[$typ]) -> Buffer<$ityp> {
let mut codes =
vortex_utils::aliases::hash_map::HashMap::<$typ, $ityp>::with_capacity(
distinct.len(),
);
for (code, &value) in distinct.iter().enumerate() {
codes.insert(value, code as $ityp);
}
let mut output = vortex_buffer::BufferMut::with_capacity(values.len());
for value in values {
// Any code lookups which fail are for nulls, so their value does not matter.
// SAFETY: we have exactly sized output to be as large as values.
unsafe { output.push_unchecked(codes.get(value).copied().unwrap_or_default()) };
}
output.freeze()
}
}
)*
};
}
impl_encode!(u8);
impl_encode!(u16);
impl_encode!(u32);
impl_encode!(u64);
impl_encode!(i8);
impl_encode!(i16);
impl_encode!(i32);
impl_encode!(i64);
#[cfg(test)]
mod tests {
use vortex_array::IntoArray;
use vortex_array::ToCanonical;
use vortex_array::arrays::BoolArray;
use vortex_array::arrays::PrimitiveArray;
use vortex_array::arrays::dict::DictArrayExt;
use vortex_array::assert_arrays_eq;
use vortex_array::validity::Validity;
use vortex_buffer::buffer;
use super::dictionary_encode;
use crate::stats::IntegerStats;
#[test]
fn test_dict_encode_integer_stats() {
let data = buffer![100i32, 200, 100, 0, 100];
let validity =
Validity::Array(BoolArray::from_iter([true, true, true, false, true]).into_array());
let array = PrimitiveArray::new(data, validity);
let stats = IntegerStats::generate_opts(
&array,
crate::stats::GenerateStatsOptions {
count_distinct_values: true,
},
);
let dict_array = dictionary_encode(array, &stats).unwrap();
assert_eq!(dict_array.values().len(), 2);
assert_eq!(dict_array.codes().len(), 5);
let expected = PrimitiveArray::new(
buffer![100i32, 200, 100, 100, 100],
Validity::Array(BoolArray::from_iter([true, true, true, false, true]).into_array()),
)
.into_array();
let undict = dict_array.as_array().to_primitive().into_array();
assert_arrays_eq!(undict, expected);
}
}