kz930 commented on code in PR #8481: URL: https://github.com/apache/texera/pull/8481#discussion_r4476200767
########## common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/binning/BinningOpDesc.scala: ########## @@ -0,0 +1,185 @@ +/* + * 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.texera.amber.operator.binning + +import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription} +import com.kjetland.jackson.jsonSchema.annotations.{JsonSchemaInject, JsonSchemaTitle} +import org.apache.texera.amber.core.tuple.{AttributeType, Schema} +import org.apache.texera.amber.core.workflow.{InputPort, OutputPort, PortIdentity} +import org.apache.texera.amber.operator.metadata.annotations.AutofillAttributeName +import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, OperatorInfo} +import org.apache.texera.amber.operator.{PythonOperatorDescriptor, StandaloneCodeGenerator} +import org.apache.texera.amber.pybuilder.PyStringTypes.EncodableString +import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.{ + PythonTemplateBuilderStringContext, + pyStringLiteral +} + +@JsonSchemaInject(json = """ +{ + "attributeTypeRules": { + "attribute": { + "enum": ["integer", "long", "double"] + } + } +} +""") +class BinningOpDesc extends PythonOperatorDescriptor with StandaloneCodeGenerator { + + @JsonProperty(required = true) + @JsonSchemaTitle("Attribute") + @JsonPropertyDescription("numeric column to cut into bins") + @AutofillAttributeName + var attribute: EncodableString = "" + + @JsonProperty(required = true, defaultValue = "equal width") + @JsonSchemaTitle("Method") + @JsonPropertyDescription("how the bins are cut") + var method: BinningMethod = BinningMethod.EQUAL_WIDTH + + @JsonProperty(required = true, defaultValue = "4") + @JsonSchemaTitle("Number of bins") + @JsonPropertyDescription("how many bins to cut the column into") + @JsonSchemaInject(json = """{"minimum": 2, "maximum": 100}""") + var bins: Int = 4 + + override def operatorInfo: OperatorInfo = + OperatorInfo( + userFriendlyName = "Binning", + operatorDescription = + "Cut a numeric column into bins, so rows can be grouped by range rather than by value", + operatorGroupName = OperatorGroupConstants.CLEANING_GROUP, + inputPorts = List(InputPort()), + // Blocking: an equal-frequency cut is made at the column's quantiles, which + // are not known until the last row has arrived. + outputPorts = List(OutputPort(blocking = true)) + ) + + /** The bin a row fell in, named after the column it was cut from. */ + private def resultColumn: String = s"${attribute}_bin" + + override def getOutputSchemas( + inputSchemas: Map[PortIdentity, Schema] + ): Map[PortIdentity, Schema] = + Map( + operatorInfo.outputPorts.head.id -> + // The bin reads as its own range, "(2.5, 5.0]", rather than as a number: + // the point of binning is a label to group by, and a number would invite + // arithmetic on what is really a name. + inputSchemas.values.head.add(resultColumn, AttributeType.STRING) + ) + + /** `duplicates="drop"` because a quantile cut can put two edges in one place + * where the values repeat, and fewer bins beats raising. + */ + private def cutArgs: String = + method match { + case BinningMethod.EQUAL_WIDTH => s"bins=$bins" + case BinningMethod.EQUAL_FREQUENCY => s"""q=$bins, duplicates="drop"""" + } + + private def cutName: String = + method match { + case BinningMethod.EQUAL_WIDTH => "pd.cut" + case BinningMethod.EQUAL_FREQUENCY => "pd.qcut" + } + + /** An empty cell has no bin, and `astype(str)` would render its absence as the + * text "nan", so the hole is kept as one. + */ + private val labelSuffix: String = + """.astype("string").astype("object").where(lambda s: s.notna(), None)""" + + /** pandas builds the edges in float64, which cannot count by one past 2**53, so a + * narrow range of large integers collapses into duplicate edges. An integer + * column is cut as its distance from the value nearest zero, which float64 holds + * exactly and which cannot overflow, and that value is added back to the labels + * in exact decimal arithmetic. Only where the plain cut raises or loses a bin, + * so every other column keeps the labels pandas gives it. + */ + private val integerShift: String = + """int(min(max(0, _binned.min()), _binned.max())) if pd.api.types.is_integer_dtype(_binned) else 0""" + + private val shiftedLabel: String = + """lambda i: "(%s, %s]" % (_low + Decimal(str(i.left)), _low + Decimal(str(i.right)))""" + + override def standaloneImports(): Seq[String] = Seq("from decimal import Decimal") + + override def generatePythonCode(): String = { + val cut = cutName + val args = cutArgs + val suffix = labelSuffix + val shift = integerShift + val label = shiftedLabel + // The result column is named in PYTHON rather than here: joining it to + // `attribute` in Scala would hand `pyb` a plain string, and the value it was + // built to protect would be spliced into the template unguarded. + // + // The guard is there because edges cannot be found in a column that holds + // nothing: an equal-width cut raises both when every cell is empty and when + // no row arrived at all. Leaving those values uncut keeps the holes, and the + // suffix turns them into the empty bins they already are. The test runs on a + // float64 view because a nullable Float64 column can store NaN, which + // `notna()` counts as a value there but the cut still cannot place. + pyb"""from pytexera import * + |import pandas as pd + |from decimal import Decimal + | + |class ProcessTableOperator(UDFTableOperator): + | + | @overrides + | def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]: + | out = table.copy() + | _column = $attribute + | _binned = out[_column] + | if _binned.astype("float64").notna().any(): + | _low = ${shift} + | _shifted = ${cut}(_binned - _low, ${args}) + | try: + | _plain = ${cut}(_binned, ${args}) + | except ValueError: + | _plain = None + | if _plain is not None and len(_plain.cat.categories) == len(_shifted.cat.categories): Review Comment: Fixed in 1a16467e6: the plain cut is now kept only when every row lands in the same bin as the shifted cut, and the spec covers your three Int64-limit values. Also merged main to clear the conflict. -- 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]
