cboumalh commented on code in PR #52883:
URL: https://github.com/apache/spark/pull/52883#discussion_r2627635596


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/tuplesketchesAggregates.scala:
##########
@@ -0,0 +1,1895 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.expressions.aggregate
+
+import org.apache.datasketches.memory.Memory
+import org.apache.datasketches.tuple.{Intersection, Sketch, Sketches, Summary, 
SummaryFactory, SummarySetOperations, Union, UpdatableSketch, 
UpdatableSketchBuilder, UpdatableSummary}
+import org.apache.datasketches.tuple.adouble.{DoubleSummary, 
DoubleSummaryDeserializer, DoubleSummaryFactory, DoubleSummarySetOperations}
+import org.apache.datasketches.tuple.aninteger.{IntegerSummary, 
IntegerSummaryDeserializer, IntegerSummaryFactory, IntegerSummarySetOperations}
+import org.apache.datasketches.tuple.strings.{ArrayOfStringsSummary, 
ArrayOfStringsSummaryDeserializer, ArrayOfStringsSummaryFactory, 
ArrayOfStringsSummarySetOperations}
+
+import org.apache.spark.SparkUnsupportedOperationException
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.{ExpressionBuilder, 
TypeCheckResult}
+import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
+import org.apache.spark.sql.catalyst.expressions.{ExpectsInputTypes, 
Expression, ExpressionDescription, Literal}
+import 
org.apache.spark.sql.catalyst.expressions.aggregate.TypedImperativeAggregate
+import org.apache.spark.sql.catalyst.plans.logical.{FunctionSignature, 
InputParameter}
+import org.apache.spark.sql.catalyst.trees.{BinaryLike, QuaternaryLike, 
TernaryLike, UnaryLike}
+import org.apache.spark.sql.catalyst.util.{ArrayData, CollationFactory, 
ThetaSketchUtils}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.internal.types.StringTypeWithCollation
+import org.apache.spark.sql.types.{AbstractDataType, ArrayType, BinaryType, 
DataType, DoubleType, FloatType, IntegerType, LongType, StringType, 
TypeCollection}
+import org.apache.spark.unsafe.types.UTF8String
+
+sealed trait TupleSketchState[S <: Summary] {
+  def serialize(): Array[Byte]
+  def eval(): Array[Byte]
+}
+case class UpdatableTupleSketchBuffer[U, S <: UpdatableSummary[U]](sketch: 
UpdatableSketch[U, S])
+    extends TupleSketchState[S] {
+  override def serialize(): Array[Byte] = sketch.compact.toByteArray
+  override def eval(): Array[Byte] = sketch.compact.toByteArray
+
+  /** Returns compact form of the sketch, needed for merge operations that 
require Sketch type. */
+  def compactSketch: Sketch[S] = sketch.compact
+}
+case class UnionTupleAggregationBuffer[S <: Summary](union: Union[S])
+    extends TupleSketchState[S] {
+  override def serialize(): Array[Byte] = union.getResult.toByteArray
+  override def eval(): Array[Byte] = union.getResult.toByteArray
+}
+case class IntersectionTupleAggregationBuffer[S <: Summary](intersection: 
Intersection[S])
+    extends TupleSketchState[S] {
+  override def serialize(): Array[Byte] = intersection.getResult.toByteArray
+  override def eval(): Array[Byte] = intersection.getResult.toByteArray
+}
+case class FinalizedTupleSketch[S <: Summary](sketch: Sketch[S]) extends 
TupleSketchState[S] {
+  override def serialize(): Array[Byte] = sketch.toByteArray
+  override def eval(): Array[Byte] = sketch.toByteArray
+}
+
+/**
+ * The TupleSketchAggDouble function utilizes a Datasketches TupleSketch 
instance to count a
+ * probabilistic approximation of the number of unique values in a given 
column with associated
+ * double type summary values, and outputs the binary representation of the 
TupleSketch.
+ *
+ * See [[https://datasketches.apache.org/docs/Tuple/TupleSketches.html]] for 
more information.
+ *
+ * @param key
+ *   key expression against which unique counting will occur
+ * @param summary
+ *   summary expression (double type) against which different mode 
aggregations will occur
+ * @param lgNomEntries
+ *   the log-base-2 of nomEntries decides the number of buckets for the sketch
+ * @param mode
+ *   the aggregation mode for numeric summaries (sum, min, max, alwaysone)
+ * @param mutableAggBufferOffset
+ *   offset for mutable aggregation buffer
+ * @param inputAggBufferOffset
+ *   offset for input aggregation buffer
+ */
+case class TupleSketchAggDouble(
+    key: Expression,
+    summary: Expression,
+    lgNomEntries: Expression,
+    mode: Expression,
+    override val mutableAggBufferOffset: Int,
+    override val inputAggBufferOffset: Int)
+    extends TupleSketchAggBase[java.lang.Double, DoubleSummary]
+    with QuaternaryLike[Expression]
+    with SummaryAggregateMode {
+
+  // Constructors
+  def this(key: Expression, summary: Expression) = {
+    this(
+      key,
+      summary,
+      Literal(ThetaSketchUtils.DEFAULT_LG_NOM_LONGS),
+      Literal(ThetaSketchUtils.MODE_SUM),
+      0,
+      0)
+  }
+
+  def this(key: Expression, summary: Expression, lgNomEntries: Expression) = {
+    this(key, summary, lgNomEntries, Literal(ThetaSketchUtils.MODE_SUM), 0, 0)
+  }
+
+  def this(key: Expression, summary: Expression, lgNomEntries: Expression, 
mode: Expression) = {
+    this(key, summary, lgNomEntries, mode, 0, 0)
+  }
+
+  /**
+   * Override inputTypes to specify key, summary (double/float), lgNomEntries 
(int), and mode
+   * (string) parameters.
+   */
+  override def inputTypes: Seq[AbstractDataType] =
+    Seq(
+      keyInputTypes,
+      summaryInputType,
+      IntegerType,
+      StringTypeWithCollation(supportsTrimCollation = true))
+
+  /**
+   * Override checkInputDataTypes to validate base inputs (key, summary, 
lgNomEntries) and mode
+   * parameter.
+   */
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val defaultCheck = checkBaseInputDataTypes()
+    if (defaultCheck.isFailure) return defaultCheck
+
+    checkModeParameter()
+  }
+
+  // Copy constructors required by ImperativeAggregate
+  override def withNewMutableAggBufferOffset(
+      newMutableAggBufferOffset: Int): TupleSketchAggDouble =
+    copy(mutableAggBufferOffset = newMutableAggBufferOffset)
+
+  override def withNewInputAggBufferOffset(newInputAggBufferOffset: Int): 
TupleSketchAggDouble =
+    copy(inputAggBufferOffset = newInputAggBufferOffset)
+
+  override protected def withNewChildrenInternal(
+      newFirst: Expression,
+      newSecond: Expression,
+      newThird: Expression,
+      newFourth: Expression): TupleSketchAggDouble =
+    copy(key = newFirst, summary = newSecond, lgNomEntries = newThird, mode = 
newFourth)
+
+  override def first: Expression = key
+  override def second: Expression = summary
+  override def third: Expression = lgNomEntries
+  override def fourth: Expression = mode
+
+  // Overrides for TypedImperativeAggregate
+  override def prettyName: String = "tuple_sketch_agg_double"
+
+  /** Specifies accepted summary input types (double and float). */
+  override protected def summaryInputType: AbstractDataType =
+    TypeCollection(DoubleType, FloatType)
+
+  /**
+   * Creates a DoubleSummaryFactory with the configured aggregation mode.
+   *
+   * @return
+   *   a DoubleSummaryFactory instance configured with the aggregation mode
+   */
+  override protected def createSummaryFactory(): SummaryFactory[DoubleSummary] 
= {
+    val mode = ThetaSketchUtils.getDoubleSummaryMode(modeInput)
+    new DoubleSummaryFactory(mode)
+  }
+
+  /**
+   * Creates DoubleSummarySetOperations for merge operations with the 
configured mode.
+   *
+   * @return
+   *   a DoubleSummarySetOperations instance configured with the aggregation 
mode
+   */
+  override protected def createSummarySetOperations(): 
SummarySetOperations[DoubleSummary] = {
+    val mode = ThetaSketchUtils.getDoubleSummaryMode(modeInput)
+    new DoubleSummarySetOperations(mode)
+  }
+
+  /**
+   * Converts Float inputs to Double, ensuring compatibility with 
DoubleSummary.
+   *
+   * @param input
+   *   the input value to normalize (Float or Double)
+   * @return
+   *   the normalized Double value
+   */
+  override protected def normalizeSummaryValue(input: Any): java.lang.Double = 
{

Review Comment:
   @dtenedor I used the `ImplicitCastInputTypes` trait instead of 
`ExpectsInputTypes`. This allows for implicit coercion with floats when using 
`theta_sketch_agg_double` as seen 
[here](https://github.com/apache/spark/blob/2bd1d48477f394bdba6ce39eeb13f22e83f731e6/sql/core/src/test/resources/sql-tests/inputs/tuplesketch.sql#L517).
 All summaries for `theta_sketch_agg_double` will be cast to DoubleType if that 
is possible, else a spark error is thrown. My only concern with this trait is 
that it allows some other interesting things such as passing lgNomEntries as a 
string `'15'` or  a double `15.0D` when it is supposed to be an integer, but it 
works after casting! Same for the summary types, it will cast in case of 
mismatch which is not always safe.



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