You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "huaxingao (via GitHub)" <gi...@apache.org> on 2024/04/21 16:10:57 UTC
[PR] feat: Support Variance [datafusion-comet]
huaxingao opened a new pull request, #297:
URL: https://github.com/apache/datafusion-comet/pull/297
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Closes #.
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
Supports `VAR_SAMP` and `VAR_POP`
The implementation mostly is the same as the DataFusion's implementation. The reason
we have our own implementation is that DataFusion has UInt64 for state_field `count`,
while Spark has Double for count. Also we adding `null_on_divide_by_zero`
to be consistent with Spark's implementation.
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
## How are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "parthchandra (via GitHub)" <gi...@apache.org>.
parthchandra commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1575356501
##########
spark/src/main/scala/org/apache/comet/serde/QueryPlanSerde.scala:
##########
@@ -426,6 +426,42 @@ object QueryPlanSerde extends Logging with ShimQueryPlanSerde {
} else {
None
}
+ case variance @ VarianceSamp(child, nullOnDivideByZero) =>
+ val childExpr = exprToProto(child, inputs, binding)
+ val dataType = serializeDataType(variance.dataType)
+
+ if (childExpr.isDefined && dataType.isDefined) {
+ val varBuilder = ExprOuterClass.VarianceSample.newBuilder()
+ varBuilder.setChild(childExpr.get)
+ varBuilder.setNullOnDivideByZero(nullOnDivideByZero)
+ varBuilder.setDatatype(dataType.get)
+
+ Some(
+ ExprOuterClass.AggExpr
+ .newBuilder()
+ .setVarianceSample(varBuilder)
+ .build())
+ } else {
+ None
Review Comment:
Could you add the explainPlan info here as well?
##########
spark/src/main/scala/org/apache/comet/serde/QueryPlanSerde.scala:
##########
@@ -426,6 +426,42 @@ object QueryPlanSerde extends Logging with ShimQueryPlanSerde {
} else {
None
}
+ case variance @ VarianceSamp(child, nullOnDivideByZero) =>
+ val childExpr = exprToProto(child, inputs, binding)
+ val dataType = serializeDataType(variance.dataType)
+
+ if (childExpr.isDefined && dataType.isDefined) {
+ val varBuilder = ExprOuterClass.VarianceSample.newBuilder()
+ varBuilder.setChild(childExpr.get)
+ varBuilder.setNullOnDivideByZero(nullOnDivideByZero)
+ varBuilder.setDatatype(dataType.get)
+
+ Some(
+ ExprOuterClass.AggExpr
+ .newBuilder()
+ .setVarianceSample(varBuilder)
+ .build())
+ } else {
+ None
+ }
+ case variancePop @ VariancePop(child, nullOnDivideByZero) =>
+ val childExpr = exprToProto(child, inputs, binding)
+ val dataType = serializeDataType(variancePop.dataType)
+
+ if (childExpr.isDefined && dataType.isDefined) {
+ val varBuilder = ExprOuterClass.VariancePopulation.newBuilder()
+ varBuilder.setChild(childExpr.get)
+ varBuilder.setNullOnDivideByZero(nullOnDivideByZero)
+ varBuilder.setDatatype(dataType.get)
+
+ Some(
+ ExprOuterClass.AggExpr
+ .newBuilder()
+ .setVariancePopulation(varBuilder)
+ .build())
+ } else {
+ None
Review Comment:
ditto, add the explainPlan info here as well
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#issuecomment-2077916473
Thanks, everyone!
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1578429132
##########
core/src/execution/datafusion/expressions/variance.rs:
##########
@@ -0,0 +1,259 @@
+// 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.
+
+//! Defines physical expressions that can evaluated at runtime during query execution
+
+use std::{any::Any, sync::Arc};
+
+use crate::execution::datafusion::expressions::{stats::StatsType, utils::down_cast_any_ref};
+use arrow::{
+ array::{ArrayRef, Float64Array},
+ compute::cast,
+ datatypes::{DataType, Field},
+};
+use datafusion::logical_expr::Accumulator;
+use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::{expressions::format_state_name, AggregateExpr, PhysicalExpr};
+
+/// VAR_SAMP and VAR_POP aggregate expression
+/// The implementation mostly is the same as the DataFusion's implementation. The reason
+/// we have our own implementation is that DataFusion has UInt64 for state_field `count`,
+/// while Spark has Double for count. Also we have added `null_on_divide_by_zero`
+/// to be consistent with Spark's implementation.
+#[derive(Debug)]
+pub struct Variance {
+ name: String,
+ expr: Arc<dyn PhysicalExpr>,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl Variance {
+ /// Create a new VARIANCE aggregate function
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ data_type: DataType,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+ ) -> Self {
+ // the result of variance just support FLOAT64 data type.
+ assert!(matches!(data_type, DataType::Float64));
+ Self {
+ name: name.into(),
+ expr,
+ stats_type,
+ null_on_divide_by_zero,
+ }
+ }
+}
+
+impl AggregateExpr for Variance {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::Float64, true))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![
+ Field::new(
+ format_state_name(&self.name, "count"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(
+ format_state_name(&self.name, "mean"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(format_state_name(&self.name, "m2"), DataType::Float64, true),
+ ])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+impl PartialEq<dyn Any> for Variance {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.name == x.name && self.expr.eq(&x.expr) && self.stats_type == x.stats_type
+ })
+ .unwrap_or(false)
+ }
+}
+
+/// An accumulator to compute variance
+#[derive(Debug)]
+pub struct VarianceAccumulator {
+ m2: f64,
+ mean: f64,
+ count: f64,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl VarianceAccumulator {
+ /// Creates a new `VarianceAccumulator`
+ pub fn try_new(s_type: StatsType, null_on_divide_by_zero: bool) -> Result<Self> {
+ Ok(Self {
+ m2: 0_f64,
+ mean: 0_f64,
+ count: 0_f64,
+ stats_type: s_type,
+ null_on_divide_by_zero,
+ })
+ }
+
+ pub fn get_count(&self) -> f64 {
+ self.count
+ }
+
+ pub fn get_mean(&self) -> f64 {
+ self.mean
+ }
+
+ pub fn get_m2(&self) -> f64 {
+ self.m2
+ }
+}
+
+impl Accumulator for VarianceAccumulator {
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![
+ ScalarValue::from(self.count),
+ ScalarValue::from(self.mean),
+ ScalarValue::from(self.m2),
+ ])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let values = &cast(&values[0], &DataType::Float64)?;
Review Comment:
`VariancePop`'s input type is `DoubleType` in Spark. I think we can be sure its input is Float64 array always.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1578498812
##########
core/src/execution/datafusion/expressions/variance.rs:
##########
@@ -0,0 +1,259 @@
+// 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.
+
+//! Defines physical expressions that can evaluated at runtime during query execution
+
+use std::{any::Any, sync::Arc};
+
+use crate::execution::datafusion::expressions::{stats::StatsType, utils::down_cast_any_ref};
+use arrow::{
+ array::{ArrayRef, Float64Array},
+ compute::cast,
+ datatypes::{DataType, Field},
+};
+use datafusion::logical_expr::Accumulator;
+use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::{expressions::format_state_name, AggregateExpr, PhysicalExpr};
+
+/// VAR_SAMP and VAR_POP aggregate expression
+/// The implementation mostly is the same as the DataFusion's implementation. The reason
+/// we have our own implementation is that DataFusion has UInt64 for state_field `count`,
+/// while Spark has Double for count. Also we have added `null_on_divide_by_zero`
+/// to be consistent with Spark's implementation.
+#[derive(Debug)]
+pub struct Variance {
+ name: String,
+ expr: Arc<dyn PhysicalExpr>,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl Variance {
+ /// Create a new VARIANCE aggregate function
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ data_type: DataType,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+ ) -> Self {
+ // the result of variance just support FLOAT64 data type.
+ assert!(matches!(data_type, DataType::Float64));
+ Self {
+ name: name.into(),
+ expr,
+ stats_type,
+ null_on_divide_by_zero,
+ }
+ }
+}
+
+impl AggregateExpr for Variance {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::Float64, true))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![
+ Field::new(
+ format_state_name(&self.name, "count"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(
+ format_state_name(&self.name, "mean"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(format_state_name(&self.name, "m2"), DataType::Float64, true),
+ ])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+impl PartialEq<dyn Any> for Variance {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.name == x.name && self.expr.eq(&x.expr) && self.stats_type == x.stats_type
+ })
+ .unwrap_or(false)
+ }
+}
+
+/// An accumulator to compute variance
+#[derive(Debug)]
+pub struct VarianceAccumulator {
+ m2: f64,
+ mean: f64,
+ count: f64,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl VarianceAccumulator {
+ /// Creates a new `VarianceAccumulator`
+ pub fn try_new(s_type: StatsType, null_on_divide_by_zero: bool) -> Result<Self> {
+ Ok(Self {
+ m2: 0_f64,
+ mean: 0_f64,
+ count: 0_f64,
+ stats_type: s_type,
+ null_on_divide_by_zero,
+ })
+ }
+
+ pub fn get_count(&self) -> f64 {
+ self.count
+ }
+
+ pub fn get_mean(&self) -> f64 {
+ self.mean
+ }
+
+ pub fn get_m2(&self) -> f64 {
+ self.m2
+ }
+}
+
+impl Accumulator for VarianceAccumulator {
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![
+ ScalarValue::from(self.count),
+ ScalarValue::from(self.mean),
+ ScalarValue::from(self.m2),
+ ])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let values = &cast(&values[0], &DataType::Float64)?;
Review Comment:
Removed. Thanks!
I have the same casting in covariance. There are a few problems I need to fix in covariance
1. remove the unnecessary cast
2. add `null_on_divide_by_zero`
3. combine `CovSample` and `CovPopulation` in `expr.proto`
I will have a PR to fix these problems.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1578070107
##########
core/src/execution/proto/expr.proto:
##########
@@ -94,9 +94,15 @@ message AggExpr {
BitXorAgg bitXorAgg = 11;
CovSample covSample = 12;
CovPopulation covPopulation = 13;
+ Variance variance = 14;
}
}
+enum StatisticsType {
Review Comment:
👍
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1577085846
##########
spark/src/main/scala/org/apache/comet/serde/QueryPlanSerde.scala:
##########
@@ -426,6 +426,42 @@ object QueryPlanSerde extends Logging with ShimQueryPlanSerde {
} else {
None
}
+ case variance @ VarianceSamp(child, nullOnDivideByZero) =>
+ val childExpr = exprToProto(child, inputs, binding)
+ val dataType = serializeDataType(variance.dataType)
+
+ if (childExpr.isDefined && dataType.isDefined) {
+ val varBuilder = ExprOuterClass.VarianceSample.newBuilder()
+ varBuilder.setChild(childExpr.get)
+ varBuilder.setNullOnDivideByZero(nullOnDivideByZero)
+ varBuilder.setDatatype(dataType.get)
+
+ Some(
+ ExprOuterClass.AggExpr
+ .newBuilder()
+ .setVarianceSample(varBuilder)
+ .build())
+ } else {
+ None
+ }
+ case variancePop @ VariancePop(child, nullOnDivideByZero) =>
+ val childExpr = exprToProto(child, inputs, binding)
+ val dataType = serializeDataType(variancePop.dataType)
+
+ if (childExpr.isDefined && dataType.isDefined) {
+ val varBuilder = ExprOuterClass.VariancePopulation.newBuilder()
+ varBuilder.setChild(childExpr.get)
+ varBuilder.setNullOnDivideByZero(nullOnDivideByZero)
+ varBuilder.setDatatype(dataType.get)
+
+ Some(
+ ExprOuterClass.AggExpr
+ .newBuilder()
+ .setVariancePopulation(varBuilder)
+ .build())
+ } else {
+ None
Review Comment:
Added. Thanks
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1577073541
##########
core/src/execution/proto/expr.proto:
##########
@@ -165,6 +167,18 @@ message CovPopulation {
DataType datatype = 4;
}
+message VarianceSample {
+ Expr child = 1;
+ bool null_on_divide_by_zero = 2;
+ DataType datatype = 3;
+}
+
+message VariancePopulation {
+ Expr child = 1;
+ bool null_on_divide_by_zero = 2;
+ DataType datatype = 3;
+}
Review Comment:
Thanks for your comment @andygrove
I am not sure if there is a way to access the field tag. I added an enum `StatisticsType` so I don't need two structs for `VarianceSample` and `VariancePopulation`. Also I think adding a `StatisticsType` is more consistent with the implementation in `variance.rs`.
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#issuecomment-2077877442
Merged. Thanks @huaxingao @andygrove @parthchandra
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1576321475
##########
core/src/execution/proto/expr.proto:
##########
@@ -165,6 +167,18 @@ message CovPopulation {
DataType datatype = 4;
}
+message VarianceSample {
+ Expr child = 1;
+ bool null_on_divide_by_zero = 2;
+ DataType datatype = 3;
+}
+
+message VariancePopulation {
+ Expr child = 1;
+ bool null_on_divide_by_zero = 2;
+ DataType datatype = 3;
+}
Review Comment:
I don't think we need to have the same struct defined twice here because we have separate field tags (14 and 15) in AggExpr to represent the two different expressions?
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#issuecomment-2069835976
cc @andygrove @viirya
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya commented on code in PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297#discussion_r1578416242
##########
core/src/execution/datafusion/expressions/variance.rs:
##########
@@ -0,0 +1,259 @@
+// 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.
+
+//! Defines physical expressions that can evaluated at runtime during query execution
+
+use std::{any::Any, sync::Arc};
+
+use crate::execution::datafusion::expressions::{stats::StatsType, utils::down_cast_any_ref};
+use arrow::{
+ array::{ArrayRef, Float64Array},
+ compute::cast,
+ datatypes::{DataType, Field},
+};
+use datafusion::logical_expr::Accumulator;
+use datafusion_common::{downcast_value, DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::{expressions::format_state_name, AggregateExpr, PhysicalExpr};
+
+/// VAR_SAMP and VAR_POP aggregate expression
+/// The implementation mostly is the same as the DataFusion's implementation. The reason
+/// we have our own implementation is that DataFusion has UInt64 for state_field `count`,
+/// while Spark has Double for count. Also we have added `null_on_divide_by_zero`
+/// to be consistent with Spark's implementation.
+#[derive(Debug)]
+pub struct Variance {
+ name: String,
+ expr: Arc<dyn PhysicalExpr>,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl Variance {
+ /// Create a new VARIANCE aggregate function
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ name: impl Into<String>,
+ data_type: DataType,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+ ) -> Self {
+ // the result of variance just support FLOAT64 data type.
+ assert!(matches!(data_type, DataType::Float64));
+ Self {
+ name: name.into(),
+ expr,
+ stats_type,
+ null_on_divide_by_zero,
+ }
+ }
+}
+
+impl AggregateExpr for Variance {
+ /// Return a reference to Any that can be used for downcasting
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn field(&self) -> Result<Field> {
+ Ok(Field::new(&self.name, DataType::Float64, true))
+ }
+
+ fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+ Ok(Box::new(VarianceAccumulator::try_new(
+ self.stats_type,
+ self.null_on_divide_by_zero,
+ )?))
+ }
+
+ fn state_fields(&self) -> Result<Vec<Field>> {
+ Ok(vec![
+ Field::new(
+ format_state_name(&self.name, "count"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(
+ format_state_name(&self.name, "mean"),
+ DataType::Float64,
+ true,
+ ),
+ Field::new(format_state_name(&self.name, "m2"), DataType::Float64, true),
+ ])
+ }
+
+ fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+ vec![self.expr.clone()]
+ }
+
+ fn name(&self) -> &str {
+ &self.name
+ }
+}
+
+impl PartialEq<dyn Any> for Variance {
+ fn eq(&self, other: &dyn Any) -> bool {
+ down_cast_any_ref(other)
+ .downcast_ref::<Self>()
+ .map(|x| {
+ self.name == x.name && self.expr.eq(&x.expr) && self.stats_type == x.stats_type
+ })
+ .unwrap_or(false)
+ }
+}
+
+/// An accumulator to compute variance
+#[derive(Debug)]
+pub struct VarianceAccumulator {
+ m2: f64,
+ mean: f64,
+ count: f64,
+ stats_type: StatsType,
+ null_on_divide_by_zero: bool,
+}
+
+impl VarianceAccumulator {
+ /// Creates a new `VarianceAccumulator`
+ pub fn try_new(s_type: StatsType, null_on_divide_by_zero: bool) -> Result<Self> {
+ Ok(Self {
+ m2: 0_f64,
+ mean: 0_f64,
+ count: 0_f64,
+ stats_type: s_type,
+ null_on_divide_by_zero,
+ })
+ }
+
+ pub fn get_count(&self) -> f64 {
+ self.count
+ }
+
+ pub fn get_mean(&self) -> f64 {
+ self.mean
+ }
+
+ pub fn get_m2(&self) -> f64 {
+ self.m2
+ }
+}
+
+impl Accumulator for VarianceAccumulator {
+ fn state(&mut self) -> Result<Vec<ScalarValue>> {
+ Ok(vec![
+ ScalarValue::from(self.count),
+ ScalarValue::from(self.mean),
+ ScalarValue::from(self.m2),
+ ])
+ }
+
+ fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
+ let values = &cast(&values[0], &DataType::Float64)?;
Review Comment:
Why we need to cast input array to Float64? Isn't it already Float64 array?
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Support Variance [datafusion-comet]
Posted by "viirya (via GitHub)" <gi...@apache.org>.
viirya merged PR #297:
URL: https://github.com/apache/datafusion-comet/pull/297
--
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-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org