vortex_array/arrays/patched/compute/
compare.rs1use vortex_buffer::BitBufferMut;
5use vortex_error::VortexExpect;
6use vortex_error::VortexResult;
7
8use crate::ArrayRef;
9use crate::Canonical;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::array::ArrayView;
13use crate::array::child_to_validity;
14use crate::arrays::BoolArray;
15use crate::arrays::ConstantArray;
16use crate::arrays::Patched;
17use crate::arrays::PrimitiveArray;
18use crate::arrays::bool::BoolArraySlotsExt;
19use crate::arrays::bool::BoolDataParts;
20use crate::arrays::patched::PatchedArrayExt;
21use crate::arrays::patched::PatchedArraySlotsExt;
22use crate::arrays::primitive::NativeValue;
23use crate::builtins::ArrayBuiltins;
24use crate::dtype::NativePType;
25use crate::match_each_native_ptype;
26use crate::scalar_fn::builtin::compare::CompareKernel;
27use crate::scalar_fn::builtin::operators::CompareOperator;
28
29impl CompareKernel for Patched {
30 fn compare(
31 lhs: ArrayView<'_, Self>,
32 rhs: &ArrayRef,
33 operator: CompareOperator,
34 ctx: &mut ExecutionCtx,
35 ) -> VortexResult<Option<ArrayRef>> {
36 if !lhs.dtype().is_primitive() {
38 return Ok(None);
39 }
40
41 let Some(constant) = rhs.as_constant() else {
43 return Ok(None);
44 };
45
46 let result = lhs
49 .inner()
50 .compare(
51 ConstantArray::new(constant.clone(), lhs.len()).into_array(),
52 operator,
53 )?
54 .execute::<Canonical>(ctx)?
55 .into_bool();
56
57 let validity = child_to_validity(result.validity_child(), result.dtype().nullability());
58 let len = result.len();
59 let BoolDataParts { bits, meta } = result.into_data().into_parts(len);
60
61 let mut bits =
62 BitBufferMut::from_buffer(bits.unwrap_host().into_mut(), meta.offset(), meta.len());
63
64 let lane_offsets = lhs.lane_offsets().clone().execute::<PrimitiveArray>(ctx)?;
65 let indices = lhs.patch_indices().clone().execute::<PrimitiveArray>(ctx)?;
66 let values = lhs.patch_values().clone().execute::<PrimitiveArray>(ctx)?;
67 let n_lanes = lhs.n_lanes();
68
69 match_each_native_ptype!(values.ptype(), |V| {
70 let offset = lhs.offset();
71 let indices = indices.as_slice::<u16>();
72 let values = values.as_slice::<V>();
73 let constant = constant
74 .as_primitive()
75 .as_::<V>()
76 .vortex_expect("compare constant not null");
77
78 let apply_patches = ApplyPatches {
79 bits: &mut bits,
80 offset,
81 n_lanes,
82 lane_offsets: lane_offsets.as_slice::<u32>(),
83 indices,
84 values,
85 constant,
86 };
87
88 match operator {
89 CompareOperator::Eq => {
90 apply_patches.apply(|l, r| NativeValue(l) == NativeValue(r))?;
91 }
92 CompareOperator::NotEq => {
93 apply_patches.apply(|l, r| NativeValue(l) != NativeValue(r))?;
94 }
95 CompareOperator::Gt => {
96 apply_patches.apply(|l, r| NativeValue(l) > NativeValue(r))?;
97 }
98 CompareOperator::Gte => {
99 apply_patches.apply(|l, r| NativeValue(l) >= NativeValue(r))?;
100 }
101 CompareOperator::Lt => {
102 apply_patches.apply(|l, r| NativeValue(l) < NativeValue(r))?;
103 }
104 CompareOperator::Lte => {
105 apply_patches.apply(|l, r| NativeValue(l) <= NativeValue(r))?;
106 }
107 }
108 });
109
110 let result = BoolArray::new(bits.freeze(), validity);
111 Ok(Some(result.into_array()))
112 }
113}
114
115struct ApplyPatches<'a, V: NativePType> {
116 bits: &'a mut BitBufferMut,
117 offset: usize,
118 n_lanes: usize,
119 lane_offsets: &'a [u32],
120 indices: &'a [u16],
121 values: &'a [V],
122 constant: V,
123}
124
125impl<V: NativePType> ApplyPatches<'_, V> {
126 fn apply<F>(self, cmp: F) -> VortexResult<()>
127 where
128 F: Fn(V, V) -> bool,
129 {
130 for index in 0..(self.lane_offsets.len() - 1) {
131 let chunk = index / self.n_lanes;
132
133 let lane_start = self.lane_offsets[index] as usize;
134 let lane_end = self.lane_offsets[index + 1] as usize;
135
136 for (&patch_index, &patch_value) in std::iter::zip(
137 &self.indices[lane_start..lane_end],
138 &self.values[lane_start..lane_end],
139 ) {
140 let bit_index = chunk * 1024 + patch_index as usize;
141 if bit_index < self.offset {
143 continue;
144 }
145 let bit_index = bit_index - self.offset;
146 if bit_index >= self.bits.len() {
147 break;
148 }
149 if cmp(patch_value, self.constant) {
150 self.bits.set(bit_index)
151 } else {
152 self.bits.unset(bit_index)
153 }
154 }
155 }
156
157 Ok(())
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use std::sync::LazyLock;
164
165 use vortex_buffer::buffer;
166 use vortex_error::VortexResult;
167 use vortex_error::vortex_err;
168 use vortex_session::VortexSession;
169
170 use crate::IntoArray;
171 use crate::VortexSessionExecute;
172 use crate::arrays::BoolArray;
173 use crate::arrays::ConstantArray;
174 use crate::arrays::Patched;
175 use crate::arrays::PrimitiveArray;
176 use crate::assert_arrays_eq;
177 use crate::optimizer::ArrayOptimizer;
178 use crate::patches::Patches;
179 use crate::scalar_fn::builtin::compare::CompareKernel;
180 use crate::scalar_fn::builtin::operators::CompareOperator;
181 use crate::validity::Validity;
182
183 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
184
185 #[test]
186 fn test_basic() {
187 let mut ctx = SESSION.create_execution_ctx();
188 let lhs = PrimitiveArray::from_iter(0u32..512).into_array();
189 let patches = Patches::new(
190 512,
191 0,
192 buffer![509u16, 510, 511].into_array(),
193 buffer![u32::MAX; 3].into_array(),
194 None,
195 &mut ctx,
196 )
197 .unwrap();
198
199 let mut ctx = SESSION.create_execution_ctx();
200
201 let lhs = Patched::from_array_and_patches(lhs, &patches, &mut ctx)
202 .unwrap()
203 .into_array()
204 .try_downcast::<Patched>()
205 .unwrap();
206
207 let rhs = ConstantArray::new(u32::MAX, 512).into_array();
208
209 let result =
210 <Patched as CompareKernel>::compare(lhs.as_view(), &rhs, CompareOperator::Eq, &mut ctx)
211 .unwrap()
212 .unwrap();
213
214 let expected =
215 BoolArray::from_indices(512, [509, 510, 511], Validity::NonNullable).into_array();
216
217 assert_arrays_eq!(result, expected, &mut ctx);
218 }
219
220 #[test]
221 fn test_with_offset() {
222 let mut ctx = SESSION.create_execution_ctx();
223 let lhs = PrimitiveArray::from_iter(0u32..512).into_array();
224 let patches = Patches::new(
225 512,
226 0,
227 buffer![5u16, 510, 511].into_array(),
228 buffer![u32::MAX; 3].into_array(),
229 None,
230 &mut ctx,
231 )
232 .unwrap();
233
234 let mut ctx = SESSION.create_execution_ctx();
235
236 let lhs = Patched::from_array_and_patches(lhs, &patches, &mut ctx).unwrap();
237 let lhs_ref = lhs
239 .into_array()
240 .slice(10..512)
241 .unwrap()
242 .optimize_ctx(&SESSION)
243 .unwrap();
244 let lhs = lhs_ref.try_downcast::<Patched>().unwrap();
245
246 assert_eq!(lhs.len(), 502);
247
248 let rhs = ConstantArray::new(u32::MAX, lhs.len()).into_array();
249
250 let result =
251 <Patched as CompareKernel>::compare(lhs.as_view(), &rhs, CompareOperator::Eq, &mut ctx)
252 .unwrap()
253 .unwrap();
254
255 let expected = BoolArray::from_indices(502, [500, 501], Validity::NonNullable).into_array();
256
257 assert_arrays_eq!(result, expected, &mut ctx);
258 }
259
260 #[test]
261 fn test_subnormal_f32() -> VortexResult<()> {
262 let mut ctx = SESSION.create_execution_ctx();
263 let subnormal: f32 = f32::MIN_POSITIVE / 2.0;
265 assert!(subnormal > 0.0 && subnormal < f32::MIN_POSITIVE);
266
267 let lhs = PrimitiveArray::from_iter((0..512).map(|i| i as f32)).into_array();
268
269 let patches = Patches::new(
270 512,
271 0,
272 buffer![509u16, 510, 511].into_array(),
273 buffer![f32::NAN, subnormal, f32::NEG_INFINITY].into_array(),
274 None,
275 &mut ctx,
276 )?;
277
278 let mut ctx = SESSION.create_execution_ctx();
279 let lhs = Patched::from_array_and_patches(lhs, &patches, &mut ctx)?
280 .into_array()
281 .try_downcast::<Patched>()
282 .map_err(|_| vortex_err!("expected patched array"))?;
283
284 let rhs = ConstantArray::new(subnormal, 512).into_array();
285
286 let result = <Patched as CompareKernel>::compare(
287 lhs.as_view(),
288 &rhs,
289 CompareOperator::Eq,
290 &mut ctx,
291 )?
292 .ok_or_else(|| vortex_err!("expected compare result"))?;
293
294 let expected = BoolArray::from_indices(512, [510], Validity::NonNullable).into_array();
295
296 assert_arrays_eq!(result, expected, &mut ctx);
297 Ok(())
298 }
299
300 #[test]
301 fn test_pos_neg_zero() -> VortexResult<()> {
302 let mut ctx = SESSION.create_execution_ctx();
303 let lhs = PrimitiveArray::from_iter([-0.0f32; 10]).into_array();
304
305 let patches = Patches::new(
306 10,
307 0,
308 buffer![5u16, 6, 7, 8, 9].into_array(),
309 buffer![f32::NAN, f32::NEG_INFINITY, 0f32, -0.0f32, f32::INFINITY].into_array(),
310 None,
311 &mut ctx,
312 )?;
313
314 let mut ctx = SESSION.create_execution_ctx();
315 let lhs = Patched::from_array_and_patches(lhs, &patches, &mut ctx)?
316 .into_array()
317 .try_downcast::<Patched>()
318 .map_err(|_| vortex_err!("expected patched array"))?;
319
320 let rhs = ConstantArray::new(0.0f32, 10).into_array();
321
322 let result = <Patched as CompareKernel>::compare(
323 lhs.as_view(),
324 &rhs,
325 CompareOperator::Eq,
326 &mut ctx,
327 )?
328 .ok_or_else(|| vortex_err!("expected compare result"))?;
329
330 let expected = BoolArray::from_indices(10, [7], Validity::NonNullable).into_array();
331
332 assert_arrays_eq!(result, expected, &mut ctx);
333
334 Ok(())
335 }
336}