UDAF
A user-defined aggregate function (UDAF) aggregates multiple input rows into a single set of values. It is particularly useful for summarizing statistical features from multimodal data, such as video, audio, or images, or consolidating multimodal labels.
The overall development process for UDAF can be modeled after scalar UDFs, with the following key considerations:
- The handler must specify a Python class that includes four essential methods: accumulate, aggregate_state, merge, and finish. The implemented accumulate, aggregate_state, and merge methods must be side-effect-free. This means their outputs should depend solely on input parameters and the current aggregation state, not on the factors such as invocation count, order, or external conditions.
- The finish method of the UDAF will be called globally only once for each group (specified by the GROUP BY clause), regardless of whether it is executed in single-CN mode or multi-DN mode.
- When defining a non-STRICT UDAF, you must ensure the accumulate method correctly handles NULL values (represented as None in Python).
- UDAFs cannot be used as window functions. That is, they cannot be used within an OVER clause.
- UDAFs do not support concurrent execution or vectorized computation.
UDAF Registration
To register a UDAF, you must provide a Python class that includes six specific instance methods: __init__, aggregate_state, accumulate, merge, finish, and __del__. These methods have predefined meanings as outlined in the table below. Beyond these requirements, you are free to add other classes or instance methods without restrictions.
| Python Class Method | Mandatory (Yes/No) | Parameter | Description | Applicable Scenarios |
|---|---|---|---|---|
| __init__(self, *args, **kwargs) | No | Parameters are passed through the with_arguments method. Only scalar values are allowed. | Constructor of the UDAF. | Initializes UDAF attributes (such as saving parameters, opening files, and establishing connections). |
| aggregate_state(self) | Yes | None. | Serializable intermediate aggregation state for cross-partition transfer. | Indicates the sharing status between accumulate and merge. |
| accumulate(self, *args, **kwargs) | Yes | Parameters are passed through the UDAF operator. Both scalar values and column names are allowed. | Incrementally updates the intermediate aggregation state. | Processes data during normal scanning phase. |
| merge(self, other_state) | Yes | Intermediate state from other partitions. | Merges states from other partitions into the current intermediate state. | Combines results across multiple partitions during distributed reduction. |
| finish(self) | Yes | None. | Outputs the final aggregated result. | Finalizes the aggregation process. |
| __del__(self) | No | Parameters cannot be passed. | Destructor of the UDAF. | Clears UDAF resources (for example, closing files and disconnecting networks). |
Example
import os import json import datetime as pydt import ibis import ibis.expr.datatypes as dt import pandas as pd from typing import Any, Dict import aura_frame as aura from aura_frame.multimodal import ai_lake from aura_frame.multimodal.function import AggregateFnBuilder target_database = "test" #Create a database in LakeFormation, for example, test. For details, see Creating a DataArts Lake Formation Instance and Planning Metadata. #Connect to the AuraJobV2 endpoint. For details about the parameters, see Establishing a Connection with the AuraJobV2 Endpoint. con = ai_lake.connect( aura_endpoint=os.getenv("aura_endpoint"), # Endpoint where the AuraJobV2 endpoint is located aura_endpoint_id=os.getenv("aura_endpoint_id"), # AuraJobV2 endpoint ID aura_endpoint_name=os.getenv("aura_endpoint_name"),# AuraJobV2 endpoint name aura_workspace_id=os.getenv("aura_workspace_id"), # Workspace ID lf_catalog_name=os.getenv("lf_catalog_name"), # LakeFormation Catalog name access_key=os.getenv("access_key"), # Access Key ID (AK) secret_key=os.getenv("secret_key"), # Secret Key (SK) default_database="postgres", # LakeFormation database name use_single_cn_mode=True, # Whether to enable the single-CN mode logging_level=logging.INFO # Set the log level. ) #Configure the UDF deployment workspace. For details about the parameters, see Configuring the UDF Deployment Workspace. con.set_function_staging_workspace( obs_directory_base=os.getenv("obs_directory_base"), obs_bucket_name=os.getenv("obs_bucket_name"), obs_server=os.getenv("obs_server"), access_key=os.getenv("access_key"), secret_key=os.getenv("secret_key"), ) class _AggState: def __init__(self): self.sum_px_qty = 0.0 self.sum_qty = 0.0 self.rows_seen = 0 self.rows_used = 0 class PythonVWAP: def __init__(self) -> None: self._state = _AggState() def accumulate(self, quantity: int, price: float, date: pydt.date, symbol: str) -> None: self._state.rows_seen += 1 if quantity is None or price is None or date is None or symbol is None: return self._state.sum_px_qty += price * quantity self._state.sum_qty += quantity self._state.rows_used += 1 @property def aggregate_state(self) -> Dict[str, Any]: return { "sum_px_qty": self._state.sum_px_qty, "sum_qty": self._state.sum_qty, "rows_seen": self._state.rows_seen, "rows_used": self._state.rows_used, } def merge(self, other_state: Dict[str, Any]) -> None: self._state.sum_px_qty += other_state.get("sum_px_qty", 0.0) self._state.sum_qty += other_state.get("sum_qty", 0.0) self._state.rows_seen += other_state.get("rows_seen", 0) self._state.rows_used += other_state.get("rows_used", 0) def finish(self) -> str: vwap = (self._state.sum_px_qty / self._state.sum_qty if self._state.sum_qty != 0 else None) result = { "vwap": round(vwap, 4) if vwap is not None else None, "total_quantity": self._state.sum_qty, "total_value": round(self._state.sum_px_qty, 2), "rows_seen": self._state.rows_seen, "rows_used": self._state.rows_used, } return json.dumps(result) try: # Create a test table and write data into it. table_name = "stock_trades" table_schema = ibis.schema({ "quantity": "int32", "price": "float64", "date": "date", "symbol": "string", }) con.sql(f'DROP TABLE IF EXISTS "{target_database}"."{table_name}";') con.create_table( table_name, schema=table_schema, database=target_database, table_format="orc", if_not_exists=True, ) con.sql(f''' INSERT INTO "{target_database}"."{table_name}" (quantity, price, date, symbol) VALUES (100, 150.25, '2024-01-15', 'AAPL'), (200, 152.30, '2024-01-16', 'AAPL'), (150, 148.50, '2024-01-17', 'AAPL'), (300, 145.75, '2024-01-15', 'GOOG'), (250, 147.80, '2024-01-16', 'GOOG'), (100, 143.20, '2024-01-17', 'GOOG'), (500, 380.50, '2024-01-15', 'MSFT'), (300, 385.40, '2024-01-16', 'MSFT'), (200, 382.10, '2024-01-17', 'MSFT') ''') con.delete_function("pythonvwap", database=target_database, if_it_exists=True) con.create_agg_function( PythonVWAP, database=target_database, signature=aura.Signature( parameters=[ aura.Parameter(name="quantity", annotation=int), aura.Parameter(name="price", annotation=float), aura.Parameter(name="date", annotation=dt.date), aura.Parameter(name="symbol", annotation=str), ], return_annotation=str, ), volatility=aura.udf.VolatilityType.IMMUTABLE, strict=False, ) ds = con.load_dataset("stock_trades", database=target_database) vwap_handler = con.get_function("pythonvwap", database=target_database) udaf_builder = AggregateFnBuilder( fn=vwap_handler, on=[ds.quantity, ds.price, ds.date, ds.symbol], as_col="VWAP_column", num_cpus=0.5, ) ds = ds.aggregate([udaf_builder], by=[ds.symbol]) res = ds.execute() df = res.copy() parsed = df["VWAP_column"].apply(json.loads).apply(pd.Series) df = pd.concat([df.drop(columns=["VWAP_column"]), parsed], axis=1) print(df) finally: con.close()
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot