vortex_array/compute/
is_constant.rs1use std::any::Any;
2use std::sync::LazyLock;
3
4use arcref::ArcRef;
5use vortex_dtype::{DType, Nullability};
6use vortex_error::{VortexError, VortexResult, vortex_bail, vortex_err};
7use vortex_scalar::Scalar;
8
9use crate::Array;
10use crate::arrays::{ConstantVTable, NullVTable};
11use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
12use crate::stats::{Precision, Stat, StatsProviderExt};
13use crate::vtable::VTable;
14
15pub fn is_constant(array: &dyn Array) -> VortexResult<Option<bool>> {
30 let opts = IsConstantOpts::default();
31 is_constant_opts(array, &opts)
32}
33
34pub fn is_constant_opts(array: &dyn Array, options: &IsConstantOpts) -> VortexResult<Option<bool>> {
38 let result = IS_CONSTANT_FN
39 .invoke(&InvocationArgs {
40 inputs: &[array.into()],
41 options,
42 })?
43 .unwrap_scalar()?
44 .as_bool()
45 .value();
46
47 Ok(result)
48}
49
50pub static IS_CONSTANT_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
51 let compute = ComputeFn::new("is_constant".into(), ArcRef::new_ref(&IsConstant));
52 for kernel in inventory::iter::<IsConstantKernelRef> {
53 compute.register_kernel(kernel.0.clone());
54 }
55 compute
56});
57
58struct IsConstant;
59
60impl ComputeFnVTable for IsConstant {
61 fn invoke(
62 &self,
63 args: &InvocationArgs,
64 kernels: &[ArcRef<dyn Kernel>],
65 ) -> VortexResult<Output> {
66 let IsConstantArgs { array, options } = IsConstantArgs::try_from(args)?;
67
68 if let Some(Precision::Exact(value)) = array.statistics().get_as::<bool>(Stat::IsConstant) {
70 return Ok(Scalar::from(Some(value)).into());
71 }
72
73 let value = is_constant_impl(array, options, kernels)?;
74
75 if options.cost == Cost::Canonicalize {
76 assert!(
78 value.is_some(),
79 "is constant in array {array} canonicalize returned None"
80 );
81 }
82
83 if let Some(value) = value {
85 array
86 .statistics()
87 .set(Stat::IsConstant, Precision::Exact(value.into()));
88 }
89
90 Ok(Scalar::from(value).into())
91 }
92
93 fn return_dtype(&self, _args: &InvocationArgs) -> VortexResult<DType> {
94 Ok(DType::Bool(Nullability::Nullable))
97 }
98
99 fn return_len(&self, _args: &InvocationArgs) -> VortexResult<usize> {
100 Ok(1)
101 }
102
103 fn is_elementwise(&self) -> bool {
104 false
105 }
106}
107
108fn is_constant_impl(
109 array: &dyn Array,
110 options: &IsConstantOpts,
111 kernels: &[ArcRef<dyn Kernel>],
112) -> VortexResult<Option<bool>> {
113 match array.len() {
114 0 => return Ok(Some(false)),
116 1 => return Ok(Some(true)),
118 _ => {}
119 }
120
121 if array.as_opt::<ConstantVTable>().is_some() || array.as_opt::<NullVTable>().is_some() {
123 return Ok(Some(true));
124 }
125
126 let all_invalid = array.all_invalid()?;
127 if all_invalid {
128 return Ok(Some(true));
129 }
130
131 let all_valid = array.all_valid()?;
132
133 if !all_valid && !all_invalid {
135 return Ok(Some(false));
136 }
137
138 let min = array
140 .statistics()
141 .get_scalar(Stat::Min, array.dtype())
142 .and_then(|p| p.as_exact());
143 let max = array
144 .statistics()
145 .get_scalar(Stat::Max, array.dtype())
146 .and_then(|p| p.as_exact());
147
148 if let Some((min, max)) = min.zip(max) {
149 if min == max {
150 return Ok(Some(true));
151 }
152 }
153
154 assert!(
155 all_valid,
156 "All values must be valid as an invariant of the VTable."
157 );
158 let args = InvocationArgs {
159 inputs: &[array.into()],
160 options,
161 };
162 for kernel in kernels {
163 if let Some(output) = kernel.invoke(&args)? {
164 return Ok(output.unwrap_scalar()?.as_bool().value());
165 }
166 }
167 if let Some(output) = array.invoke(&IS_CONSTANT_FN, &args)? {
168 return Ok(output.unwrap_scalar()?.as_bool().value());
169 }
170
171 log::debug!(
172 "No is_constant implementation found for {}",
173 array.encoding_id()
174 );
175
176 if options.cost == Cost::Canonicalize && !array.is_canonical() {
177 let array = array.to_canonical()?;
178 let is_constant = is_constant_opts(array.as_ref(), options)?;
179 return Ok(is_constant);
180 }
181
182 Ok(None)
184}
185
186pub struct IsConstantKernelRef(ArcRef<dyn Kernel>);
187inventory::collect!(IsConstantKernelRef);
188
189pub trait IsConstantKernel: VTable {
190 fn is_constant(&self, array: &Self::Array, opts: &IsConstantOpts)
197 -> VortexResult<Option<bool>>;
198}
199
200#[derive(Debug)]
201pub struct IsConstantKernelAdapter<V: VTable>(pub V);
202
203impl<V: VTable + IsConstantKernel> IsConstantKernelAdapter<V> {
204 pub const fn lift(&'static self) -> IsConstantKernelRef {
205 IsConstantKernelRef(ArcRef::new_ref(self))
206 }
207}
208
209impl<V: VTable + IsConstantKernel> Kernel for IsConstantKernelAdapter<V> {
210 fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
211 let args = IsConstantArgs::try_from(args)?;
212 let Some(array) = args.array.as_opt::<V>() else {
213 return Ok(None);
214 };
215 let is_constant = V::is_constant(&self.0, array, args.options)?;
216 Ok(Some(Scalar::from(is_constant).into()))
217 }
218}
219
220struct IsConstantArgs<'a> {
221 array: &'a dyn Array,
222 options: &'a IsConstantOpts,
223}
224
225impl<'a> TryFrom<&InvocationArgs<'a>> for IsConstantArgs<'a> {
226 type Error = VortexError;
227
228 fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
229 if value.inputs.len() != 1 {
230 vortex_bail!("Expected 1 input, found {}", value.inputs.len());
231 }
232 let array = value.inputs[0]
233 .array()
234 .ok_or_else(|| vortex_err!("Expected input 0 to be an array"))?;
235 let options = value
236 .options
237 .as_any()
238 .downcast_ref::<IsConstantOpts>()
239 .ok_or_else(|| vortex_err!("Expected options to be of type IsConstantOpts"))?;
240 Ok(Self { array, options })
241 }
242}
243
244#[derive(Clone, Copy, Debug, Eq, PartialEq)]
248pub enum Cost {
249 Negligible,
251 Specialized,
255 Canonicalize,
258}
259
260#[derive(Clone, Debug)]
262pub struct IsConstantOpts {
263 pub cost: Cost,
265}
266
267impl Default for IsConstantOpts {
268 fn default() -> Self {
269 Self {
270 cost: Cost::Canonicalize,
271 }
272 }
273}
274
275impl Options for IsConstantOpts {
276 fn as_any(&self) -> &dyn Any {
277 self
278 }
279}
280
281impl IsConstantOpts {
282 pub fn is_negligible_cost(&self) -> bool {
283 self.cost == Cost::Negligible
284 }
285}