Dandandan commented on code in PR #6904:
URL: https://github.com/apache/arrow-datafusion/pull/6904#discussion_r1258639145
##########
datafusion/physical-expr/src/aggregate/average.rs:
##########
@@ -383,6 +435,189 @@ impl RowAccumulator for AvgRowAccumulator {
}
}
+/// An accumulator to compute the average of `[PrimitiveArray<T>]`.
+/// Stores values as native types, and does overflow checking
+///
+/// F: Function that calcuates the average value from a sum of
+/// T::Native and a total count
+#[derive(Debug)]
+struct AvgGroupsAccumulator<T, F>
+where
+ T: ArrowNumericType + Send,
+ F: Fn(T::Native, u64) -> Result<T::Native> + Send,
+{
+ /// The type of the internal sum
+ sum_data_type: DataType,
+
+ /// The type of the returned sum
+ return_data_type: DataType,
+
+ /// Count per group (use u64 to make UInt64Array)
+ counts: Vec<u64>,
+
+ /// Sums per group, stored as the native type
+ sums: Vec<T::Native>,
+
+ /// Track nulls in the input / filters
+ null_state: NullState,
+
+ /// Function that computes the final average (value / count)
+ avg_fn: F,
+}
+
+impl<T, F> AvgGroupsAccumulator<T, F>
+where
+ T: ArrowNumericType + Send,
+ F: Fn(T::Native, u64) -> Result<T::Native> + Send,
+{
+ pub fn new(sum_data_type: &DataType, return_data_type: &DataType, avg_fn:
F) -> Self {
+ debug!(
+ "AvgGroupsAccumulator ({}, sum type: {sum_data_type:?}) -->
{return_data_type:?}",
+ std::any::type_name::<T>()
+ );
+
+ Self {
+ return_data_type: return_data_type.clone(),
+ sum_data_type: sum_data_type.clone(),
+ counts: vec![],
+ sums: vec![],
+ null_state: NullState::new(),
+ avg_fn,
+ }
+ }
+}
+
+impl<T, F> GroupsAccumulator for AvgGroupsAccumulator<T, F>
+where
+ T: ArrowNumericType + Send,
+ F: Fn(T::Native, u64) -> Result<T::Native> + Send,
+{
+ fn update_batch(
+ &mut self,
+ values: &[ArrayRef],
+ group_indices: &[usize],
+ opt_filter: Option<&arrow_array::BooleanArray>,
+ total_num_groups: usize,
+ ) -> Result<()> {
+ assert_eq!(values.len(), 1, "single argument to update_batch");
+ let values = values.get(0).unwrap().as_primitive::<T>();
+
+ // increment counts, update sums
+ self.counts.resize(total_num_groups, 0);
+ self.sums.resize(total_num_groups, T::default_value());
+ self.null_state.accumulate(
+ group_indices,
+ values,
+ opt_filter,
+ total_num_groups,
+ |group_index, new_value| {
+ let sum = &mut self.sums[group_index];
+ *sum = sum.add_wrapping(new_value);
+
+ self.counts[group_index] += 1;
+ },
+ );
+
+ Ok(())
+ }
+
+ fn merge_batch(
+ &mut self,
+ values: &[ArrayRef],
+ group_indices: &[usize],
+ opt_filter: Option<&arrow_array::BooleanArray>,
+ total_num_groups: usize,
+ ) -> Result<()> {
+ assert_eq!(values.len(), 2, "two arguments to merge_batch");
+ // first batch is counts, second is partial sums
+ let partial_counts =
values.get(0).unwrap().as_primitive::<UInt64Type>();
+ let partial_sums = values.get(1).unwrap().as_primitive::<T>();
+ // update counts with partial counts
+ self.counts.resize(total_num_groups, 0);
+ self.null_state.accumulate(
+ group_indices,
+ partial_counts,
+ opt_filter,
+ total_num_groups,
+ |group_index, partial_count| {
+ self.counts[group_index] += partial_count;
+ },
+ );
+
+ // update sums
+ self.sums
+ .resize_with(total_num_groups, || T::default_value());
+ self.null_state.accumulate(
+ group_indices,
+ partial_sums,
+ opt_filter,
+ total_num_groups,
+ |group_index, new_value: <T as ArrowPrimitiveType>::Native| {
+ let sum = &mut self.sums[group_index];
+ *sum = sum.add_wrapping(new_value);
+ },
+ );
+
+ Ok(())
+ }
+
+ fn evaluate(&mut self) -> Result<ArrayRef> {
+ let counts = std::mem::take(&mut self.counts);
+ let sums = std::mem::take(&mut self.sums);
+ let nulls = self.null_state.build();
+
+ assert_eq!(counts.len(), sums.len());
+
+ // don't evaluate averages with null inputs to avoid errors on null
vaues
+ let array: PrimitiveArray<T> = if let Some(nulls) = nulls.as_ref() {
+ assert_eq!(nulls.len(), sums.len());
+ let mut builder =
PrimitiveBuilder::<T>::with_capacity(nulls.len());
+ let iter =
sums.into_iter().zip(counts.into_iter()).zip(nulls.iter());
+
+ for ((sum, count), is_valid) in iter {
+ if is_valid {
+ builder.append_value((self.avg_fn)(sum, count)?)
+ } else {
+ builder.append_null();
+ }
+ }
+ builder.finish()
+ } else {
+ let averages: Vec<T::Native> = sums
+ .into_iter()
+ .zip(counts.into_iter())
+ .map(|(sum, count)| (self.avg_fn)(sum, count))
+ .collect::<Result<Vec<_>>>()?;
+ PrimitiveArray::new(averages.into(), nulls) // no copy
+ };
+
+ // fix up decimal precision and scale for decimals
+ let array = adjust_output_array(&self.return_data_type,
Arc::new(array))?;
+
+ Ok(array)
+ }
+
+ // return arrays for sums and counts
+ fn state(&mut self) -> Result<Vec<ArrayRef>> {
+ let nulls = self.null_state.build();
+ let counts = std::mem::take(&mut self.counts);
+ let counts = UInt64Array::from(counts); // zero copy
+
+ let sums = std::mem::take(&mut self.sums);
+ let sums = PrimitiveArray::<T>::new(sums.into(), nulls); // zero copy
+ let sums = adjust_output_array(&self.sum_data_type, Arc::new(sums))?;
+
+ Ok(vec![
+ Arc::new(counts) as ArrayRef,
+ Arc::new(sums) as ArrayRef,
+ ])
+ }
+
+ fn size(&self) -> usize {
+ self.counts.capacity() * std::mem::size_of::<usize>()
Review Comment:
* `size` of sums is missing?
* counts should be multiplied with `std::mem::size_of::<u64>()`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]