goldmedal commented on code in PR #12273:
URL: https://github.com/apache/datafusion/pull/12273#discussion_r1739743588


##########
datafusion/functions-aggregate/src/kurtosis_pop.rs:
##########
@@ -0,0 +1,199 @@
+// 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 arrow::array::{Array, ArrayRef, Float64Array, UInt64Array};
+use arrow::compute::cast;
+use arrow_schema::{DataType, Field};
+use datafusion_common::{
+    downcast_value, plan_err, unwrap_or_internal_err, DataFusionError, Result,
+    ScalarValue,
+};
+use datafusion_expr::{Accumulator, AggregateUDFImpl, Signature, Volatility};
+use datafusion_functions_aggregate_common::accumulator::{
+    AccumulatorArgs, StateFieldsArgs,
+};
+use std::any::Any;
+use std::fmt::Debug;
+
+make_udaf_expr_and_func!(
+    KurtosisPopFunction,
+    kurtosis_pop,
+    x,
+    "Calculates the excess kurtosis (Fisher’s definition) without bias 
correction.",
+    kurtosis_pop_udaf
+);
+
+pub struct KurtosisPopFunction {
+    signature: Signature,
+}
+
+impl Debug for KurtosisPopFunction {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("KurtosisPopFunction")
+            .field("signature", &self.signature)
+            .finish()
+    }
+}
+
+impl Default for KurtosisPopFunction {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl KurtosisPopFunction {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::numeric(1, Volatility::Immutable),
+        }
+    }
+}
+
+impl AggregateUDFImpl for KurtosisPopFunction {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "kurtosis_pop"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if !arg_types[0].is_null() && !arg_types[0].is_numeric() {
+            return plan_err!("KurtosisPop requires numeric input types");
+        }
+
+        Ok(DataType::Float64)
+    }
+
+    fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<Field>> {
+        Ok(vec![
+            Field::new("count", DataType::UInt64, true),
+            Field::new("sum", DataType::Float64, true),
+            Field::new("sum_sqr", DataType::Float64, true),
+            Field::new("sum_cub", DataType::Float64, true),
+            Field::new("sum_four", DataType::Float64, true),
+        ])
+    }
+
+    fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn 
Accumulator>> {
+        Ok(Box::new(KurtosisPopAccumulator::new()))
+    }
+}
+
+#[derive(Debug, Default)]
+pub struct KurtosisPopAccumulator {
+    count: u64,
+    sum: f64,
+    sum_sqr: f64,
+    sum_cub: f64,
+    sum_four: f64,
+}
+
+impl KurtosisPopAccumulator {
+    pub fn new() -> Self {
+        Self {
+            count: 0,
+            sum: 0.0,
+            sum_sqr: 0.0,
+            sum_cub: 0.0,
+            sum_four: 0.0,
+        }
+    }
+}
+
+impl Accumulator for KurtosisPopAccumulator {
+    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+        let values = &cast(&values[0], &DataType::Float64)?;
+        let mut arr = downcast_value!(values, Float64Array).iter().flatten();
+        for i in 0..values.len() {
+            let value = if values.is_valid(i) { arr.next() } else { None };
+
+            if value.is_none() {
+                continue;
+            }
+
+            let value = unwrap_or_internal_err!(value);
+            self.count += 1;
+            self.sum += value;
+            self.sum_sqr += value.powi(2);
+            self.sum_cub += value.powi(3);
+            self.sum_four += value.powi(4);
+        }
+        Ok(())
+    }
+
+    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
+        let counts = downcast_value!(states[0], UInt64Array);
+        let sums = downcast_value!(states[1], Float64Array);
+        let sum_sqrs = downcast_value!(states[2], Float64Array);
+        let sum_cubs = downcast_value!(states[3], Float64Array);
+        let sum_fours = downcast_value!(states[4], Float64Array);
+
+        for i in 0..counts.len() {
+            let c = counts.value(i);
+            if c == 0 {
+                continue;
+            }
+            self.count += c;
+            self.sum += sums.value(i);
+            self.sum_sqr += sum_sqrs.value(i);
+            self.sum_cub += sum_cubs.value(i);
+            self.sum_four += sum_fours.value(i);
+        }
+
+        Ok(())
+    }
+
+    fn evaluate(&mut self) -> Result<ScalarValue> {
+        if self.count < 1 {
+            return Ok(ScalarValue::Float64(None));
+        }
+
+        let count_64 = 1_f64 / self.count as f64;
+        let m4 = count_64
+            * (self.sum_four - 4.0 * self.sum_cub * self.sum * count_64
+                + 6.0 * self.sum_sqr * self.sum.powi(2) * count_64.powi(2)
+                - 3.0 * self.sum.powi(4) * count_64.powi(3));

Review Comment:
   I followed the DuckDB way to get the divisor here.
   
   
https://github.com/duckdb/duckdb/blob/a706958d15a6fc7fd47d65d22de7deac63613458/src/core_functions/aggregate/distributive/kurtosis.cpp#L69
   
   The result will same as DuckDB but it's different from Clickhouse.
   
   I did some test to compare the behavior between DuckDB and Clickhouse:
   ## DuckDB
   ```
   D  SELECT kurtosis_pop(col) FROM VALUES (1), (10), (100), (10), (1) as 
tab(col);
   ┌─────────────────────┐
   │  kurtosis_pop(col)  │
   │       double        │
   ├─────────────────────┤
   │ 0.19432323191699075 │
   └─────────────────────┘
   ```
   ## Clickhouse
   ```
   :) SELECT kurtPop(value) FROM (SELECT arrayJoin([1, 10, 100, 10, 1]) AS 
value);
   
   SELECT kurtPop(value)
   FROM
   (
       SELECT arrayJoin([1, 10, 100, 10, 1]) AS value
   )
   
   Query id: abdea377-40b1-4437-a87a-4814f11cc866
   
      ┌─────kurtPop(value)─┐
   1. │ 3.1943232319169903 │
      └────────────────────┘
   
   1 row in set. Elapsed: 0.002 sec. 
   ```
   
   Because DuckDB's kurtosis_pop calculates the population kurtosis using 
Fisher's definition, which results in the excess kurtosis, i.e., the value 
minus 3, ClickHouse directly provides the population kurtosis value without 
subtracting 3.
   
   However, if we change the code like
   ```suggestion
           let count_64 = self.count as f64;
           let m4 = 
           (self.sum_four - 4.0 * self.sum_cub * self.sum / count_64
                   + 6.0 * self.sum_sqr * self.sum.powi(2) / count_64.powi(2)
                   - 3.0 * self.sum.powi(4) / count_64.powi(3)) / count_64;
   ```
   
   The result will same as Clikhouse, `3.1943232319169903 - 3 = 
0.1943232319169903`



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to