-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathbinary_numeric.rs
More file actions
401 lines (357 loc) · 14.3 KB
/
binary_numeric.rs
File metadata and controls
401 lines (357 loc) · 14.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
//! # Binary Numeric Conformance Tests
//!
//! This module provides conformance testing for binary numeric operations on Vortex arrays.
//! It ensures that all numeric array encodings produce identical results when performing
//! arithmetic operations (add, subtract, multiply, divide).
//!
//! ## Test Strategy
//!
//! For each array encoding, we test:
//! 1. All binary numeric operators against a constant scalar value
//! 2. Both left-hand and right-hand side operations (e.g., array + 1 and 1 + array)
//! 3. That results match the canonical primitive array implementation
//!
//! ## Supported Operations
//!
//! - Addition (`+`)
//! - Subtraction (`-`)
//! - Multiplication (`*`)
//! - Division (`/`)
use itertools::Itertools;
use num_traits::Num;
use vortex_error::VortexExpect;
use vortex_error::vortex_err;
use vortex_error::vortex_panic;
use crate::ArrayRef;
use crate::IntoArray;
use crate::LEGACY_SESSION;
use crate::RecursiveCanonical;
use crate::ToCanonical;
use crate::VortexSessionExecute;
use crate::arrays::ConstantArray;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::NativePType;
use crate::dtype::PType;
use crate::scalar::NumericOperator;
use crate::scalar::PrimitiveScalar;
use crate::scalar::Scalar;
fn to_vec_of_scalar(array: &ArrayRef) -> Vec<Scalar> {
// Not fast, but obviously correct
(0..array.len())
.map(|index| {
array
.scalar_at(index)
.vortex_expect("scalar_at should succeed in conformance test")
})
.collect_vec()
}
/// Tests binary numeric operations for conformance across array encodings.
///
/// # Type Parameters
///
/// * `T` - The native numeric type (e.g., i32, f64) that the array contains
///
/// # Arguments
///
/// * `array` - The array to test, which should contain numeric values of type `T`
///
/// # Test Details
///
/// This function:
/// 1. Canonicalizes the input array to primitive form to get expected values
/// 2. Tests all binary numeric operators against a constant value of 1
/// 3. Verifies results match the expected primitive array computation
/// 4. Tests both array-operator-scalar and scalar-operator-array forms
/// 5. Gracefully skips operations that would cause overflow/underflow
///
/// # Panics
///
/// Panics if:
/// - The array cannot be converted to primitive form
/// - Results don't match expected values (for operations that don't overflow)
fn test_binary_numeric_conformance<T: NativePType + Num + Copy>(array: ArrayRef)
where
Scalar: From<T>,
{
// First test with the standard scalar value of 1
test_standard_binary_numeric::<T>(array.clone());
// Then test edge cases
test_binary_numeric_edge_cases(array);
}
fn test_standard_binary_numeric<T: NativePType + Num + Copy>(array: ArrayRef)
where
Scalar: From<T>,
{
let canonicalized_array = array.to_primitive();
let original_values = to_vec_of_scalar(&canonicalized_array.into_array());
let one = T::from(1)
.ok_or_else(|| vortex_err!("could not convert 1 into array native type"))
.vortex_expect("operation should succeed in conformance test");
let scalar_one = Scalar::from(one)
.cast(array.dtype())
.vortex_expect("operation should succeed in conformance test");
let operators: [NumericOperator; 4] = [
NumericOperator::Add,
NumericOperator::Sub,
NumericOperator::Mul,
NumericOperator::Div,
];
for operator in operators {
let op = operator;
let rhs_const = ConstantArray::new(scalar_one.clone(), array.len()).into_array();
// Test array operator scalar (e.g., array + 1)
let result = array
.binary(rhs_const.clone(), op.into())
.vortex_expect("apply shouldn't fail")
.execute::<RecursiveCanonical>(&mut LEGACY_SESSION.create_execution_ctx())
.map(|c| c.0.into_array());
// Skip this operator if the entire operation fails
// This can happen for some edge cases in specific encodings
let Ok(result) = result else {
continue;
};
let actual_values = to_vec_of_scalar(&result);
// Check each element for overflow/underflow
let expected_results: Vec<Option<Scalar>> = original_values
.iter()
.map(|x| {
x.as_primitive()
.checked_binary_numeric(&scalar_one.as_primitive(), op)
.map(<Scalar as From<PrimitiveScalar<'_>>>::from)
})
.collect();
// For elements that didn't overflow, check they match
for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
if let Some(expected_value) = expected {
assert_eq!(
actual,
expected_value,
"Binary numeric operation failed for encoding {} at index {}: \
({array:?})[{idx}] {operator:?} {scalar_one} \
expected {expected_value:?}, got {actual:?}",
array.encoding_id(),
idx,
);
}
}
// Test scalar operator array (e.g., 1 + array)
let result = rhs_const.binary(array.clone(), op.into()).and_then(|a| {
a.execute::<RecursiveCanonical>(&mut LEGACY_SESSION.create_execution_ctx())
.map(|c| c.0.into_array())
});
// Skip this operator if the entire operation fails
let Ok(result) = result else {
continue;
};
let actual_values = to_vec_of_scalar(&result);
// Check each element for overflow/underflow
let expected_results: Vec<Option<Scalar>> = original_values
.iter()
.map(|x| {
scalar_one
.as_primitive()
.checked_binary_numeric(&x.as_primitive(), op)
.map(<Scalar as From<PrimitiveScalar<'_>>>::from)
})
.collect();
// For elements that didn't overflow, check they match
for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
if let Some(expected_value) = expected {
assert_eq!(
actual,
expected_value,
"Binary numeric operation failed for encoding {} at index {}: \
{scalar_one} {operator:?} ({array:?})[{idx}] \
expected {expected_value:?}, got {actual:?}",
array.encoding_id(),
idx,
);
}
}
}
}
/// Entry point for binary numeric conformance testing for any array type.
///
/// This function automatically detects the array's numeric type and runs
/// the appropriate tests. It's designed to be called from rstest parameterized
/// tests without requiring explicit type parameters.
///
/// # Example
///
/// ```ignore
/// #[rstest]
/// #[case::i32_array(create_i32_array())]
/// #[case::f64_array(create_f64_array())]
/// fn test_my_encoding_binary_numeric(#[case] array: MyArray) {
/// test_binary_numeric_array(array.into_array());
/// }
/// ```
pub fn test_binary_numeric_array(array: ArrayRef) {
match array.dtype() {
DType::Primitive(ptype, _) => match ptype {
PType::I8 => test_binary_numeric_conformance::<i8>(array),
PType::I16 => test_binary_numeric_conformance::<i16>(array),
PType::I32 => test_binary_numeric_conformance::<i32>(array),
PType::I64 => test_binary_numeric_conformance::<i64>(array),
PType::U8 => test_binary_numeric_conformance::<u8>(array),
PType::U16 => test_binary_numeric_conformance::<u16>(array),
PType::U32 => test_binary_numeric_conformance::<u32>(array),
PType::U64 => test_binary_numeric_conformance::<u64>(array),
PType::F16 => {
// F16 not supported in num-traits, skip
eprintln!("Skipping f16 binary numeric tests (not supported)");
}
PType::F32 => test_binary_numeric_conformance::<f32>(array),
PType::F64 => test_binary_numeric_conformance::<f64>(array),
},
dtype => vortex_panic!(
"Binary numeric tests are only supported for primitive numeric types, got {dtype}",
),
}
}
/// Tests binary numeric operations with edge case scalar values.
///
/// This function tests operations with scalar values:
/// - Zero (identity for addition/subtraction, absorbing for multiplication)
/// - Negative one (tests signed arithmetic)
/// - Maximum value (tests overflow behavior)
/// - Minimum value (tests underflow behavior)
fn test_binary_numeric_edge_cases(array: ArrayRef) {
match array.dtype() {
DType::Primitive(ptype, _) => match ptype {
PType::I8 => test_binary_numeric_edge_cases_signed::<i8>(array),
PType::I16 => test_binary_numeric_edge_cases_signed::<i16>(array),
PType::I32 => test_binary_numeric_edge_cases_signed::<i32>(array),
PType::I64 => test_binary_numeric_edge_cases_signed::<i64>(array),
PType::U8 => test_binary_numeric_edge_cases_unsigned::<u8>(array),
PType::U16 => test_binary_numeric_edge_cases_unsigned::<u16>(array),
PType::U32 => test_binary_numeric_edge_cases_unsigned::<u32>(array),
PType::U64 => test_binary_numeric_edge_cases_unsigned::<u64>(array),
PType::F16 => {
eprintln!("Skipping f16 edge case tests (not supported)");
}
PType::F32 => test_binary_numeric_edge_cases_float::<f32>(array),
PType::F64 => test_binary_numeric_edge_cases_float::<f64>(array),
},
dtype => vortex_panic!(
"Binary numeric edge case tests are only supported for primitive numeric types, got {dtype}"
),
}
}
fn test_binary_numeric_edge_cases_signed<T>(array: ArrayRef)
where
T: NativePType + Num + Copy + std::fmt::Debug + num_traits::Bounded + num_traits::Signed,
Scalar: From<T>,
{
// Test with zero
test_binary_numeric_with_scalar(array.clone(), T::zero());
// Test with -1
test_binary_numeric_with_scalar(array.clone(), -T::one());
// Test with max value
test_binary_numeric_with_scalar(array.clone(), T::max_value());
// Test with min value
test_binary_numeric_with_scalar(array, T::min_value());
}
fn test_binary_numeric_edge_cases_unsigned<T>(array: ArrayRef)
where
T: NativePType + Num + Copy + std::fmt::Debug + num_traits::Bounded,
Scalar: From<T>,
{
// Test with zero
test_binary_numeric_with_scalar(array.clone(), T::zero());
// Test with max value
test_binary_numeric_with_scalar(array, T::max_value());
}
fn test_binary_numeric_edge_cases_float<T>(array: ArrayRef)
where
T: NativePType + Num + Copy + std::fmt::Debug + num_traits::Float,
Scalar: From<T>,
{
// Test with zero
test_binary_numeric_with_scalar(array.clone(), T::zero());
// Test with -1
test_binary_numeric_with_scalar(array.clone(), -T::one());
// Test with max value
test_binary_numeric_with_scalar(array.clone(), T::max_value());
// Test with min value
test_binary_numeric_with_scalar(array.clone(), T::min_value());
// Test with small positive value
test_binary_numeric_with_scalar(array.clone(), T::epsilon());
// Test with min positive value (subnormal)
test_binary_numeric_with_scalar(array.clone(), T::min_positive_value());
// Test with special float values (NaN, Infinity)
test_binary_numeric_with_scalar(array.clone(), T::nan());
test_binary_numeric_with_scalar(array.clone(), T::infinity());
test_binary_numeric_with_scalar(array, T::neg_infinity());
}
fn test_binary_numeric_with_scalar<T>(array: ArrayRef, scalar_value: T)
where
T: NativePType + Num + Copy + std::fmt::Debug,
Scalar: From<T>,
{
let canonicalized_array = array.to_primitive();
let original_values = to_vec_of_scalar(&canonicalized_array.into_array());
let scalar = Scalar::from(scalar_value)
.cast(array.dtype())
.vortex_expect("operation should succeed in conformance test");
// Only test operators that make sense for the given scalar
let operators = if scalar_value == T::zero() {
// Skip division by zero
vec![
NumericOperator::Add,
NumericOperator::Sub,
NumericOperator::Mul,
]
} else {
vec![
NumericOperator::Add,
NumericOperator::Sub,
NumericOperator::Mul,
NumericOperator::Div,
]
};
for operator in operators {
let op = operator;
let rhs_const = ConstantArray::new(scalar.clone(), array.len()).into_array();
// Test array operator scalar
let result = array
.binary(rhs_const, op.into())
.vortex_expect("apply failed")
.execute::<RecursiveCanonical>(&mut LEGACY_SESSION.create_execution_ctx())
.map(|x| x.0.into_array());
// Skip if the entire operation fails
// TODO(joe): this is odd.
if result.is_err() {
continue;
}
let result = result.vortex_expect("operation should succeed in conformance test");
let actual_values = to_vec_of_scalar(&result);
// Check each element for overflow/underflow
let expected_results: Vec<Option<Scalar>> = original_values
.iter()
.map(|x| {
x.as_primitive()
.checked_binary_numeric(&scalar.as_primitive(), op)
.map(<Scalar as From<PrimitiveScalar<'_>>>::from)
})
.collect();
// For elements that didn't overflow, check they match
for (idx, (actual, expected)) in actual_values.iter().zip(&expected_results).enumerate() {
if let Some(expected_value) = expected {
assert_eq!(
actual,
expected_value,
"Binary numeric operation failed for encoding {} at index {} with scalar {:?}: \
({array:?})[{idx}] {operator:?} {scalar} \
expected {expected_value:?}, got {actual:?}",
array.encoding_id(),
idx,
scalar_value,
);
}
}
}
}