hsiang-c commented on code in PR #6180:
URL: https://github.com/apache/datafusion-comet/pull/6180#discussion_r4127979936


##########
native/spark-expr/src/predicate_funcs/at_least_n_non_nulls.rs:
##########
@@ -0,0 +1,553 @@
+// 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::fmt::{Display, Formatter};
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, RecordBatch};
+use arrow::buffer::{BooleanBuffer, Buffer};
+use arrow::compute::cast;
+use arrow::datatypes::{DataType, Float32Type, Float64Type, Schema};
+use datafusion::common::{Result, ScalarValue};
+use datafusion::physical_expr::expressions::{Column, Literal};
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+
+/// Spark's per-row count of non-null, non-NaN children, stopping once `n` is 
reached.
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct AtLeastNNonNulls {
+    n: i32,
+    children: Vec<Arc<dyn PhysicalExpr>>,
+}
+
+impl AtLeastNNonNulls {
+    pub fn new(n: i32, children: Vec<Arc<dyn PhysicalExpr>>) -> Self {
+        Self { n, children }
+    }
+
+    // Sub-word batches do not amortize the bitmap counter's bookkeeping. Keep
+    // the row counter for these batches, including single-row scalar inputs.
+    fn evaluate_small_batch(&self, batch: &RecordBatch) -> 
Result<ColumnarValue> {
+        let mut counts = vec![0; batch.num_rows()];
+        let mut remaining = batch.num_rows();
+        for child in &self.children {
+            if remaining == 0 {
+                break;
+            }
+            // Column/literal reads cannot raise per-row errors or have side 
effects. Avoid
+            // filtering the input batch for the common DataFrame.na.drop 
attribute inputs.
+            let value =
+                if remaining == batch.num_rows() || child.is::<Column>() || 
child.is::<Literal>() {
+                    child.evaluate(batch)?
+                } else {
+                    let selection = BooleanArray::new(
+                        BooleanBuffer::collect_bool(counts.len(), |i| 
counts[i] < self.n),
+                        None,
+                    );
+                    child.evaluate_selection(batch, &selection)?
+                };
+            let scalar = matches!(value, ColumnarValue::Scalar(_));
+            let array = value.into_array(if scalar { 1 } else { 
batch.num_rows() })?;
+            let valid = valid_values(&array)?;
+            if scalar {
+                if valid.value(0) {
+                    for count in &mut counts {
+                        if *count < self.n {
+                            *count += 1;
+                            remaining -= usize::from(*count == self.n);
+                        }
+                    }
+                }
+            } else {
+                for row in valid.set_indices() {
+                    if counts[row] < self.n {
+                        counts[row] += 1;
+                        remaining -= usize::from(counts[row] == self.n);
+                    }
+                }
+            }
+        }
+        Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+            BooleanBuffer::collect_bool(counts.len(), |i| counts[i] >= self.n),
+            None,
+        ))))
+    }
+}
+
+impl Display for AtLeastNNonNulls {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "atleastnnonnulls({}, {:?})", self.n, self.children)
+    }
+}
+
+impl PhysicalExpr for AtLeastNNonNulls {
+    fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        Display::fmt(self, f)
+    }
+
+    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+        Ok(DataType::Boolean)
+    }
+
+    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+        Ok(false)
+    }
+
+    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+        if self.n <= 0 {
+            return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))));
+        }
+        // The standard na.drop("all"/"any") cases reduce to bitmap OR/AND and 
do not
+        // need a per-row counter. For AND, still evaluate every child: Spark 
does not
+        // skip later expressions just because a row can no longer reach the 
threshold.
+        if self.n == 1 || self.n as usize == self.children.len() {
+            let all = self.n != 1;
+            let mut result = if all {
+                BooleanBuffer::new_set(batch.num_rows())
+            } else {
+                BooleanBuffer::new_unset(batch.num_rows())
+            };
+            for child in &self.children {
+                if batch.num_rows() == 0 || (!all && result.count_set_bits() 
== batch.num_rows()) {
+                    break;
+                }
+                let value = if all || child.is::<Column>() || 
child.is::<Literal>() {
+                    child.evaluate(batch)?
+                } else {
+                    child.evaluate_selection(batch, 
&BooleanArray::new(!&result, None))?
+                };
+                let valid = 
valid_values(&value.into_array(batch.num_rows())?)?;
+                result = if all {
+                    &result & &valid
+                } else {
+                    &result | &valid
+                };
+            }
+            return Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+                result, None,
+            ))));
+        }
+        if batch.num_rows() < 64 {

Review Comment:
   Why `64`?



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to