1use std::any::Any;
2use std::sync::LazyLock;
3
4use arcref::ArcRef;
5use vortex_dtype::DType;
6use vortex_error::{VortexError, VortexResult, vortex_bail, vortex_err};
7use vortex_scalar::{NumericOperator, Scalar};
8
9use crate::arrays::ConstantArray;
10use crate::arrow::{Datum, from_arrow_array_with_len};
11use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
12use crate::vtable::VTable;
13use crate::{Array, ArrayRef, IntoArray};
14
15pub fn add(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
17 numeric(lhs, rhs, NumericOperator::Add)
18}
19
20pub fn add_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
22 numeric(
23 lhs,
24 &ConstantArray::new(rhs, lhs.len()).into_array(),
25 NumericOperator::Add,
26 )
27}
28
29pub fn sub(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
31 numeric(lhs, rhs, NumericOperator::Sub)
32}
33
34pub fn sub_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
36 numeric(
37 lhs,
38 &ConstantArray::new(rhs, lhs.len()).into_array(),
39 NumericOperator::Sub,
40 )
41}
42
43pub fn mul(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
45 numeric(lhs, rhs, NumericOperator::Mul)
46}
47
48pub fn mul_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
50 numeric(
51 lhs,
52 &ConstantArray::new(rhs, lhs.len()).into_array(),
53 NumericOperator::Mul,
54 )
55}
56
57pub fn div(lhs: &dyn Array, rhs: &dyn Array) -> VortexResult<ArrayRef> {
59 numeric(lhs, rhs, NumericOperator::Div)
60}
61
62pub fn div_scalar(lhs: &dyn Array, rhs: Scalar) -> VortexResult<ArrayRef> {
64 numeric(
65 lhs,
66 &ConstantArray::new(rhs, lhs.len()).into_array(),
67 NumericOperator::Mul,
68 )
69}
70
71pub fn numeric(lhs: &dyn Array, rhs: &dyn Array, op: NumericOperator) -> VortexResult<ArrayRef> {
73 NUMERIC_FN
74 .invoke(&InvocationArgs {
75 inputs: &[lhs.into(), rhs.into()],
76 options: &op,
77 })?
78 .unwrap_array()
79}
80
81pub struct NumericKernelRef(ArcRef<dyn Kernel>);
82inventory::collect!(NumericKernelRef);
83
84pub trait NumericKernel: VTable {
85 fn numeric(
86 &self,
87 array: &Self::Array,
88 other: &dyn Array,
89 op: NumericOperator,
90 ) -> VortexResult<Option<ArrayRef>>;
91}
92
93#[derive(Debug)]
94pub struct NumericKernelAdapter<V: VTable>(pub V);
95
96impl<V: VTable + NumericKernel> NumericKernelAdapter<V> {
97 pub const fn lift(&'static self) -> NumericKernelRef {
98 NumericKernelRef(ArcRef::new_ref(self))
99 }
100}
101
102impl<V: VTable + NumericKernel> Kernel for NumericKernelAdapter<V> {
103 fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
104 let inputs = NumericArgs::try_from(args)?;
105 let Some(lhs) = inputs.lhs.as_opt::<V>() else {
106 return Ok(None);
107 };
108 Ok(V::numeric(&self.0, lhs, inputs.rhs, inputs.operator)?.map(|array| array.into()))
109 }
110}
111
112pub static NUMERIC_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
113 let compute = ComputeFn::new("numeric".into(), ArcRef::new_ref(&Numeric));
114 for kernel in inventory::iter::<NumericKernelRef> {
115 compute.register_kernel(kernel.0.clone());
116 }
117 compute
118});
119
120struct Numeric;
121
122impl ComputeFnVTable for Numeric {
123 fn invoke(
124 &self,
125 args: &InvocationArgs,
126 kernels: &[ArcRef<dyn Kernel>],
127 ) -> VortexResult<Output> {
128 let NumericArgs { lhs, rhs, operator } = NumericArgs::try_from(args)?;
129
130 for kernel in kernels {
132 if let Some(output) = kernel.invoke(args)? {
133 return Ok(output);
134 }
135 }
136 if let Some(output) = lhs.invoke(&NUMERIC_FN, args)? {
137 return Ok(output);
138 }
139
140 let inverted_args = InvocationArgs {
142 inputs: &[rhs.into(), lhs.into()],
143 options: &operator.swap(),
144 };
145 for kernel in kernels {
146 if let Some(output) = kernel.invoke(&inverted_args)? {
147 return Ok(output);
148 }
149 }
150 if let Some(output) = rhs.invoke(&NUMERIC_FN, &inverted_args)? {
151 return Ok(output);
152 }
153
154 log::debug!(
155 "No numeric implementation found for LHS {}, RHS {}, and operator {:?}",
156 lhs.encoding_id(),
157 rhs.encoding_id(),
158 operator,
159 );
160
161 Ok(arrow_numeric(lhs, rhs, operator)?.into())
163 }
164
165 fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
166 let NumericArgs { lhs, rhs, .. } = NumericArgs::try_from(args)?;
167 if !matches!(
168 (lhs.dtype(), rhs.dtype()),
169 (DType::Primitive(..), DType::Primitive(..)) | (DType::Decimal(..), DType::Decimal(..))
170 ) || !lhs.dtype().eq_ignore_nullability(rhs.dtype())
171 {
172 vortex_bail!(
173 "Numeric operations are only supported on two arrays sharing the same numeric type: {} {}",
174 lhs.dtype(),
175 rhs.dtype()
176 )
177 }
178 Ok(lhs.dtype().union_nullability(rhs.dtype().nullability()))
179 }
180
181 fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
182 let NumericArgs { lhs, rhs, .. } = NumericArgs::try_from(args)?;
183 if lhs.len() != rhs.len() {
184 vortex_bail!(
185 "Numeric operations aren't supported on arrays of different lengths {} {}",
186 lhs.len(),
187 rhs.len()
188 )
189 }
190 Ok(lhs.len())
191 }
192
193 fn is_elementwise(&self) -> bool {
194 true
195 }
196}
197
198struct NumericArgs<'a> {
199 lhs: &'a dyn Array,
200 rhs: &'a dyn Array,
201 operator: NumericOperator,
202}
203
204impl<'a> TryFrom<&InvocationArgs<'a>> for NumericArgs<'a> {
205 type Error = VortexError;
206
207 fn try_from(args: &InvocationArgs<'a>) -> VortexResult<Self> {
208 if args.inputs.len() != 2 {
209 vortex_bail!("Numeric operations require exactly 2 inputs");
210 }
211 let lhs = args.inputs[0]
212 .array()
213 .ok_or_else(|| vortex_err!("LHS is not an array"))?;
214 let rhs = args.inputs[1]
215 .array()
216 .ok_or_else(|| vortex_err!("RHS is not an array"))?;
217 let operator = *args
218 .options
219 .as_any()
220 .downcast_ref::<NumericOperator>()
221 .ok_or_else(|| vortex_err!("Operator is not a numeric operator"))?;
222 Ok(Self { lhs, rhs, operator })
223 }
224}
225
226impl Options for NumericOperator {
227 fn as_any(&self) -> &dyn Any {
228 self
229 }
230}
231
232fn arrow_numeric(
237 lhs: &dyn Array,
238 rhs: &dyn Array,
239 operator: NumericOperator,
240) -> VortexResult<ArrayRef> {
241 let nullable = lhs.dtype().is_nullable() || rhs.dtype().is_nullable();
242 let len = lhs.len();
243
244 let left = Datum::try_new(lhs)?;
245 let right = Datum::try_new(rhs)?;
246
247 let array = match operator {
248 NumericOperator::Add => arrow_arith::numeric::add(&left, &right)?,
249 NumericOperator::Sub => arrow_arith::numeric::sub(&left, &right)?,
250 NumericOperator::RSub => arrow_arith::numeric::sub(&right, &left)?,
251 NumericOperator::Mul => arrow_arith::numeric::mul(&left, &right)?,
252 NumericOperator::Div => arrow_arith::numeric::div(&left, &right)?,
253 NumericOperator::RDiv => arrow_arith::numeric::div(&right, &left)?,
254 };
255
256 from_arrow_array_with_len(array.as_ref(), len, nullable)
257}
258
259#[cfg(test)]
260mod test {
261 use vortex_buffer::buffer;
262 use vortex_scalar::Scalar;
263
264 use crate::IntoArray;
265 use crate::arrays::PrimitiveArray;
266 use crate::canonical::ToCanonical;
267 use crate::compute::sub_scalar;
268
269 #[test]
270 fn test_scalar_subtract_unsigned() {
271 let values = buffer![1u16, 2, 3].into_array();
272 let results = sub_scalar(&values, 1u16.into())
273 .unwrap()
274 .to_primitive()
275 .unwrap()
276 .as_slice::<u16>()
277 .to_vec();
278 assert_eq!(results, &[0u16, 1, 2]);
279 }
280
281 #[test]
282 fn test_scalar_subtract_signed() {
283 let values = buffer![1i64, 2, 3].into_array();
284 let results = sub_scalar(&values, (-1i64).into())
285 .unwrap()
286 .to_primitive()
287 .unwrap()
288 .as_slice::<i64>()
289 .to_vec();
290 assert_eq!(results, &[2i64, 3, 4]);
291 }
292
293 #[test]
294 fn test_scalar_subtract_nullable() {
295 let values = PrimitiveArray::from_option_iter([Some(1u16), Some(2), None, Some(3)]);
296 let result = sub_scalar(values.as_ref(), Some(1u16).into())
297 .unwrap()
298 .to_primitive()
299 .unwrap();
300
301 let actual = (0..result.len())
302 .map(|index| result.scalar_at(index).unwrap())
303 .collect::<Vec<_>>();
304 assert_eq!(
305 actual,
306 vec![
307 Scalar::from(Some(0u16)),
308 Scalar::from(Some(1u16)),
309 Scalar::from(None::<u16>),
310 Scalar::from(Some(2u16))
311 ]
312 );
313 }
314
315 #[test]
316 fn test_scalar_subtract_float() {
317 let values = buffer![1.0f64, 2.0, 3.0].into_array();
318 let to_subtract = -1f64;
319 let results = sub_scalar(&values, to_subtract.into())
320 .unwrap()
321 .to_primitive()
322 .unwrap()
323 .as_slice::<f64>()
324 .to_vec();
325 assert_eq!(results, &[2.0f64, 3.0, 4.0]);
326 }
327
328 #[test]
329 fn test_scalar_subtract_float_underflow_is_ok() {
330 let values = buffer![f32::MIN, 2.0, 3.0].into_array();
331 let _results = sub_scalar(&values, 1.0f32.into()).unwrap();
332 let _results = sub_scalar(&values, f32::MAX.into()).unwrap();
333 }
334
335 #[test]
336 fn test_scalar_subtract_type_mismatch_fails() {
337 let values = buffer![1u64, 2, 3].into_array();
338 let _results =
340 sub_scalar(&values, 1.5f64.into()).expect_err("Expected type mismatch error");
341 }
342}