datafusion_functions_aggregate_common/aggregate/groups_accumulator/prim_op.rs
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use std::mem::size_of;
use std::sync::Arc;
use arrow::array::{ArrayRef, AsArray, BooleanArray, PrimitiveArray};
use arrow::buffer::NullBuffer;
use arrow::compute;
use arrow::datatypes::ArrowPrimitiveType;
use arrow::datatypes::DataType;
use datafusion_common::{internal_datafusion_err, DataFusionError, Result};
use datafusion_expr_common::groups_accumulator::{EmitTo, GroupsAccumulator};
use super::accumulate::NullState;
/// An accumulator that implements a single operation over
/// [`ArrowPrimitiveType`] where the accumulated state is the same as
/// the input type (such as `Sum`)
///
/// F: The function to apply to two elements. The first argument is
/// the existing value and should be updated with the second value
/// (e.g. [`BitAndAssign`] style).
///
/// [`BitAndAssign`]: std::ops::BitAndAssign
#[derive(Debug)]
pub struct PrimitiveGroupsAccumulator<T, F>
where
T: ArrowPrimitiveType + Send,
F: Fn(&mut T::Native, T::Native) + Send + Sync,
{
/// values per group, stored as the native type
values: Vec<T::Native>,
/// The output type (needed for Decimal precision and scale)
data_type: DataType,
/// The starting value for new groups
starting_value: T::Native,
/// Track nulls in the input / filters
null_state: NullState,
/// Function that computes the primitive result
prim_fn: F,
}
impl<T, F> PrimitiveGroupsAccumulator<T, F>
where
T: ArrowPrimitiveType + Send,
F: Fn(&mut T::Native, T::Native) + Send + Sync,
{
pub fn new(data_type: &DataType, prim_fn: F) -> Self {
Self {
values: vec![],
data_type: data_type.clone(),
null_state: NullState::new(),
starting_value: T::default_value(),
prim_fn,
}
}
/// Set the starting values for new groups
pub fn with_starting_value(mut self, starting_value: T::Native) -> Self {
self.starting_value = starting_value;
self
}
}
impl<T, F> GroupsAccumulator for PrimitiveGroupsAccumulator<T, F>
where
T: ArrowPrimitiveType + Send,
F: Fn(&mut T::Native, T::Native) + Send + Sync,
{
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> Result<()> {
assert_eq!(values.len(), 1, "single argument to update_batch");
let values = values[0].as_primitive::<T>();
// update values
self.values.resize(total_num_groups, self.starting_value);
// NullState dispatches / handles tracking nulls and groups that saw no values
self.null_state.accumulate(
group_indices,
values,
opt_filter,
total_num_groups,
|group_index, new_value| {
let value = &mut self.values[group_index];
(self.prim_fn)(value, new_value);
},
);
Ok(())
}
fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef> {
let values = emit_to.take_needed(&mut self.values);
let nulls = self.null_state.build(emit_to);
let values = PrimitiveArray::<T>::new(values.into(), Some(nulls)) // no copy
.with_data_type(self.data_type.clone());
Ok(Arc::new(values))
}
fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
self.evaluate(emit_to).map(|arr| vec![arr])
}
fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> Result<()> {
// update / merge are the same
self.update_batch(values, group_indices, opt_filter, total_num_groups)
}
/// Converts an input batch directly to a state batch
///
/// The state is:
/// - self.prim_fn for all non null, non filtered values
/// - null otherwise
///
fn convert_to_state(
&self,
values: &[ArrayRef],
opt_filter: Option<&BooleanArray>,
) -> Result<Vec<ArrayRef>> {
let values = values[0].as_primitive::<T>().clone();
// Initializing state with starting values
let initial_state =
PrimitiveArray::<T>::from_value(self.starting_value, values.len());
// Recalculating values in case there is filter
let values = match opt_filter {
None => values,
Some(filter) => {
let (filter_values, filter_nulls) = filter.clone().into_parts();
// Calculating filter mask as a result of bitand of filter, and converting it to null buffer
let filter_bool = match filter_nulls {
Some(filter_nulls) => filter_nulls.inner() & &filter_values,
None => filter_values,
};
let filter_nulls = NullBuffer::from(filter_bool);
// Rebuilding input values with a new nulls mask, which is equal to
// the union of original nulls and filter mask
let (dt, values_buf, original_nulls) = values.into_parts();
let nulls_buf =
NullBuffer::union(original_nulls.as_ref(), Some(&filter_nulls));
PrimitiveArray::<T>::new(values_buf, nulls_buf).with_data_type(dt)
}
};
let state_values = compute::binary_mut(initial_state, &values, |mut x, y| {
(self.prim_fn)(&mut x, y);
x
});
let state_values = state_values
.map_err(|_| {
internal_datafusion_err!(
"initial_values underlying buffer must not be shared"
)
})?
.map_err(DataFusionError::from)?
.with_data_type(self.data_type.clone());
Ok(vec![Arc::new(state_values)])
}
fn supports_convert_to_state(&self) -> bool {
true
}
fn size(&self) -> usize {
self.values.capacity() * size_of::<T::Native>() + self.null_state.size()
}
}