kz930 commented on code in PR #8709:
URL: https://github.com/apache/texera/pull/8709#discussion_r4466462684


##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/aggregate/AggregateOpDesc.scala:
##########
@@ -141,4 +148,267 @@ class AggregateOpDesc extends LogicalOp {
       inputPorts = List(InputPort()),
       outputPorts = List(OutputPort())
     )
+
+  /** The engine aggregates in two phases across partitions; one process needs
+    * only the one groupby, or a single-row reduction when no key is grouped 
on.
+    *
+    * Must run before `getPhysicalPlan`, which rewrites `aggregations` in 
place:
+    * it turns COUNT into SUM for the final phase, and this reads them as
+    * written.
+    *
+    * SUM and AVERAGE follow the column's DECLARED type: a holed INTEGER column
+    * arrives as a float, and an INTEGER and a LONG arrive alike.
+    */
+  override def generateStandaloneCode(inputSchemas: Map[PortIdentity, 
Schema]): String = {
+    val schema = inputSchemas.get(operatorInfo.inputPorts.head.id)
+    build(name => schema.flatMap(s => 
Try(s.getAttribute(name).getType).toOption))
+  }
+
+  override def generateStandaloneCode(): String = build(_ => None)
+
+  override def standaloneHelpers(): Seq[String] =
+    Seq(StandaloneHelpers.AttributeCasts, AggregateOpDesc.Helpers)
+
+  private def build(declaredType: String => Option[AttributeType]): String = {
+    val keys = Option(groupByKeys).getOrElse(List())
+    val aggs = Option(aggregations).getOrElse(List())
+
+    if (keys.isEmpty) {
+      val rowEntries = aggs
+        .map(agg =>
+          s"    ${pyStringLiteral(agg.resultAttribute)}: ${aggExprScalar(agg, 
declaredType)},"
+        )
+        .mkString("\n")
+      val resultsLit =
+        aggs.map(agg => pyStringLiteral(agg.resultAttribute)).mkString("[", ", 
", "]")
+      // The engine opens a group when a row arrives, so with no rows there is 
no
+      // group to finish and it emits nothing, not one row of COUNT 0.
+      s"""if len(in1df):
+         |    out1df = pd.DataFrame([{
+         |${rowEntries.linesIterator.map("    " + _).mkString("\n")}
+         |    }])
+         |else:
+         |    out1df = pd.DataFrame(columns=$resultsLit)""".stripMargin
+    } else {
+      val keysLit = keys.map(pyStringLiteral).mkString("[", ", ", "]")
+      // Grouped and joined back by the id of each row's group, never by the
+      // key values, which would pair NaN keys again.
+      val joinLines = aggs
+        .map(agg =>
+          s"out1df = out1df.join(${aggExprGroupby(agg, "_texera_agg_groups", 
declaredType)})"
+        )
+        .mkString("\n")
+      s"""[_texera_agg_ids] = _texera_key_codes(in1df[$keysLit])
+         |_texera_agg_groups = in1df.groupby(_texera_agg_ids, sort=False)
+         |_texera_agg_first = ~_texera_agg_ids.duplicated()
+         |out1df = in1df.loc[_texera_agg_first, 
$keysLit].set_axis(_texera_agg_ids[_texera_agg_first])
+         |$joinLines
+         |out1df = out1df.reset_index(drop=True)""".stripMargin
+    }
+  }
+
+  private def aggExprScalar(
+      agg: AggregationOperation,
+      declaredType: String => Option[AttributeType]
+  ): String = {
+    val attrLit =
+      if (agg.attribute == null || agg.attribute.isEmpty) "None"
+      else pyStringLiteral(agg.attribute)
+    val declared = 
Option(agg.attribute).filter(_.nonEmpty).flatMap(declaredType)
+    agg.aggFunction match {
+      case AggregationFunction.SUM =>
+        declared match {
+          case Some(AttributeType.INTEGER)   => 
s"_texera_agg_int_sum(in1df[$attrLit])"
+          case Some(AttributeType.TIMESTAMP) => 
s"_texera_agg_ts_sum(in1df[$attrLit])"
+          case Some(AttributeType.DOUBLE)    => 
s"_texera_agg_double_sum(in1df[$attrLit])"
+          case _                             => s"in1df[$attrLit].sum()"
+        }
+      case AggregationFunction.AVERAGE =>
+        declared match {
+          case Some(AttributeType.TIMESTAMP) => 
s"_texera_agg_ts_mean(in1df[$attrLit])"
+          case Some(AttributeType.DOUBLE)    => 
s"_texera_agg_double_mean(in1df[$attrLit])"
+          case _                             => s"in1df[$attrLit].mean()"
+        }
+      case AggregationFunction.MIN =>
+        declared match {
+          case Some(AttributeType.DOUBLE)    => 
s"_texera_agg_double_min(in1df[$attrLit])"
+          case Some(AttributeType.TIMESTAMP) => 
s"_texera_agg_ts_min(in1df[$attrLit])"
+          case _                             => s"in1df[$attrLit].min()"
+        }
+      case AggregationFunction.MAX =>
+        declared match {
+          case Some(AttributeType.DOUBLE)    => 
s"_texera_agg_double_max(in1df[$attrLit])"
+          case Some(AttributeType.TIMESTAMP) => 
s"_texera_agg_ts_max(in1df[$attrLit])"
+          case _                             => s"in1df[$attrLit].max()"
+        }
+      case AggregationFunction.COUNT =>
+        if (agg.attribute == null || agg.attribute.isEmpty) "int(len(in1df))"

Review Comment:
   Fixed in b5c207cbd. Both COUNT branches now use `trim.isEmpty`, so a 
whitespace attribute counts every row as the engine does.



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

Reply via email to