vortex_array/arrays/scalar_fn/vtable/
mod.rs1mod operations;
4mod validity;
5
6use std::hash::Hash;
7use std::hash::Hasher;
8use std::marker::PhantomData;
9use std::ops::Deref;
10
11use itertools::Itertools;
12use validity::ValidityArray;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_error::vortex_ensure;
16use vortex_error::vortex_ensure_eq;
17use vortex_error::vortex_panic;
18use vortex_session::VortexSession;
19
20use crate::ArrayEq;
21use crate::ArrayHash;
22use crate::ArrayRef;
23use crate::EqMode;
24use crate::IntoArray;
25use crate::array::Array;
26use crate::array::ArrayId;
27use crate::array::ArrayParts;
28use crate::array::ArrayView;
29use crate::array::VTable;
30use crate::array::ValidityVTable;
31use crate::array::with_empty_buffers;
32use crate::arrays::scalar_fn::array::ScalarFnArrayExt;
33use crate::arrays::scalar_fn::array::ScalarFnData;
34use crate::arrays::scalar_fn::rules::PARENT_RULES;
35use crate::arrays::scalar_fn::rules::RULES;
36use crate::buffer::BufferHandle;
37use crate::dtype::DType;
38use crate::executor::ExecutionCtx;
39use crate::executor::ExecutionResult;
40use crate::matcher::Matcher;
41use crate::scalar_fn;
42use crate::scalar_fn::ArrayReduceNode;
43use crate::scalar_fn::ReduceNode;
44use crate::scalar_fn::ReduceNodeValidity;
45use crate::scalar_fn::ScalarFnId;
46use crate::scalar_fn::VecExecutionArgs;
47use crate::serde::ArrayChildren;
48use crate::validity::Validity;
49
50pub type ScalarFnArray = Array<ScalarFn>;
52
53#[derive(Clone, Debug)]
54pub struct ScalarFn {
55 pub(super) id: ScalarFnId,
56}
57
58impl ArrayHash for ScalarFnData {
59 fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
60 self.scalar_fn().hash(state);
61 }
62}
63
64impl ArrayEq for ScalarFnData {
65 fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
66 self.scalar_fn() == other.scalar_fn()
67 }
68}
69
70impl VTable for ScalarFn {
71 type TypedArrayData = ScalarFnData;
72 type OperationsVTable = Self;
73 type ValidityVTable = Self;
74
75 fn id(&self) -> ArrayId {
76 self.id
77 }
78
79 fn validate(
80 &self,
81 data: &ScalarFnData,
82 dtype: &DType,
83 len: usize,
84 slots: &[Option<ArrayRef>],
85 ) -> VortexResult<()> {
86 let scalar_fn = data.scalar_fn();
87 vortex_ensure_eq!(
88 scalar_fn.id(),
89 self.id,
90 "ScalarFnArray data scalar_fn does not match vtable",
91 );
92
93 let missing_children = slots.iter().filter(|slot| slot.is_none()).count();
94 vortex_ensure_eq!(
95 missing_children,
96 0,
97 "ScalarFnArray requires every child slot to be present",
98 );
99
100 let arity = scalar_fn.signature().arity();
101 vortex_ensure!(
102 arity.matches(slots.len()),
103 "ScalarFnArray requires {arity} children, got {}",
104 slots.len()
105 );
106 vortex_ensure!(
107 slots.iter().flatten().all(|c| c.len() == len),
108 "All child arrays must have the same length as the scalar function array"
109 );
110
111 let child_dtypes = slots
112 .iter()
113 .flatten()
114 .map(|c| c.dtype().clone())
115 .collect_vec();
116 vortex_ensure_eq!(
117 scalar_fn.return_dtype(&child_dtypes)?,
118 *dtype,
119 "ScalarFnArray dtype does not match scalar function return dtype",
120 );
121 Ok(())
122 }
123
124 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
125 0
126 }
127
128 fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
129 vortex_panic!("ScalarFnArray buffer index {idx} out of bounds")
130 }
131
132 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
133 None
134 }
135
136 fn with_buffers(
137 &self,
138 array: ArrayView<'_, Self>,
139 buffers: &[BufferHandle],
140 ) -> VortexResult<ArrayParts<Self>> {
141 with_empty_buffers(self, array, buffers)
142 }
143
144 fn serialize(
145 _array: ArrayView<'_, Self>,
146 _session: &VortexSession,
147 ) -> VortexResult<Option<Vec<u8>>> {
148 Ok(None)
150 }
151
152 fn deserialize(
153 &self,
154 _dtype: &DType,
155 _len: usize,
156 _metadata: &[u8],
157 _buffers: &[BufferHandle],
158 _children: &dyn ArrayChildren,
159 _session: &VortexSession,
160 ) -> VortexResult<ArrayParts<Self>> {
161 vortex_bail!("Deserialization of ScalarFnVTable metadata is not supported");
162 }
163
164 fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String {
165 array
166 .scalar_fn()
167 .signature()
168 .child_name(idx)
169 .as_ref()
170 .to_string()
171 }
172
173 fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
174 let args = VecExecutionArgs::new(array.children(), array.len());
175 array
176 .scalar_fn()
177 .execute(&args, ctx)
178 .map(ExecutionResult::done)
179 }
180
181 fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
182 RULES.evaluate(array)
183 }
184
185 fn reduce_parent(
186 array: ArrayView<'_, Self>,
187 parent: &ArrayRef,
188 child_idx: usize,
189 ) -> VortexResult<Option<ArrayRef>> {
190 PARENT_RULES.evaluate(array, parent, child_idx)
191 }
192}
193
194#[derive(Debug)]
196pub struct AnyScalarFn;
197impl Matcher for AnyScalarFn {
198 type Match<'a> = ArrayView<'a, ScalarFn>;
199
200 fn matches(array: &ArrayRef) -> bool {
201 array.is::<ScalarFn>()
202 }
203
204 fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
205 array.as_opt::<ScalarFn>()
206 }
207}
208
209#[derive(Debug, Default)]
211pub struct ExactScalarFn<F: scalar_fn::ScalarFnVTable>(PhantomData<F>);
212
213impl<F: scalar_fn::ScalarFnVTable> Matcher for ExactScalarFn<F> {
214 type Match<'a> = ScalarFnArrayView<'a, F>;
215
216 fn matches(array: &ArrayRef) -> bool {
217 if let Some(scalar_fn_array) = array.as_opt::<ScalarFn>() {
218 scalar_fn_array.data().scalar_fn().is::<F>()
219 } else {
220 false
221 }
222 }
223
224 fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
225 let scalar_fn_array = array.as_opt::<ScalarFn>()?;
226 let scalar_fn_data = scalar_fn_array.data();
227 let scalar_fn = scalar_fn_data.scalar_fn().downcast_ref::<F>()?;
228 Some(ScalarFnArrayView {
229 array,
230 vtable: scalar_fn.vtable(),
231 options: scalar_fn.options(),
232 })
233 }
234}
235
236pub struct ScalarFnArrayView<'a, F: scalar_fn::ScalarFnVTable> {
237 array: &'a ArrayRef,
238 pub vtable: &'a F,
239 pub options: &'a F::Options,
240}
241
242impl<F: scalar_fn::ScalarFnVTable> Deref for ScalarFnArrayView<'_, F> {
243 type Target = ArrayRef;
244
245 fn deref(&self) -> &Self::Target {
246 self.array
247 }
248}
249
250impl ValidityVTable<ScalarFn> for ScalarFn {
251 fn validity(view: ArrayView<'_, ScalarFn>) -> VortexResult<Validity> {
252 let node = ArrayReduceNode::new(view.as_ref());
253 Ok(Validity::Array(match node.validity()? {
254 ReduceNodeValidity::Reduced(reduced) => reduced.into_array(),
255 ReduceNodeValidity::Irreducible => ValidityArray::new(node.into_array()).into_array(),
256 }))
257 }
258}