Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Aggregate Function geomean (mosaic-sql) #684

Merged
merged 3 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/api/sql/aggregate-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ Create an aggregate function that calculates the sum of the input _expression_.

Create an aggregate function that calculates the product of the input _expression_.

## geomean

`geomean(expression)`

Create an aggregate function that calculates the geometric mean of the input _expression_.

## median

`median(expression)`
Expand Down
19 changes: 18 additions & 1 deletion packages/core/src/preagg/sufficient-statistics.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AggregateNode, and, argmax, argmin, count, div, ExprNode, isNotNull, max, min, mul, pow, regrAvgX, regrAvgY, regrCount, sql, sqrt, sub, sum } from '@uwdata/mosaic-sql';
import { AggregateNode, and, argmax, argmin, count, div, ExprNode, isNotNull, max, min, mul, pow, product, regrAvgX, regrAvgY, regrCount, sql, sqrt, sub, sum } from '@uwdata/mosaic-sql';
import { fnv_hash } from '../util/hash.js';

/**
Expand All @@ -18,6 +18,8 @@ export function sufficientStatistics(node, preagg, avg) {
return sumExpr(preagg, node);
case 'avg':
return avgExpr(preagg, node);
case 'geomean':
return geomeanExpr(preagg, node);
case 'arg_max':
return argmaxExpr(preagg, node);
case 'arg_min':
Expand Down Expand Up @@ -155,6 +157,21 @@ function avgExpr(preagg, node) {
return div(sum(mul(as, name)), expr);
}

/**
* Generate an expression for calculating geometric means over data dimensions.
* As a side effect, this method adds a column to the input *preagg* object
* to track the count of non-null values per-partition.
* @param {Record<string, ExprNode>} preagg A map of columns (such as
* sufficient statistics) to pre-aggregate.
* @param {AggregateNode} [node] The originating aggregate function call.
* @returns {ExprNode} An aggregate expression over pre-aggregated dimensions.
*/
function geomeanExpr(preagg, node) {
const as = addStat(preagg, node);
const { expr, name } = countExpr(preagg, node);
return pow(product(pow(as, name)), div(1, expr));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks "theoretically" correct to me: given a set per-bin geometric means, exponentiate by the (bin-level) count to "undo" the bin-level nth-root, multiply the results, then take the (global-level) nth-root.

However, might this suffer from overflow? That intermediate product could get very large. (The same result as if we just used product as the sufficient statistic rather than geomean, which would also simplify the overall scheme to just a single pow call for the nth-root.)

This might be worth testing more with large numbers. If we see issues, a more robust alternative would be to instead use the sum of log values as the sufficient statistic. Then the output aggregate expression would be exp(div(sum(as), expr)).

Copy link
Contributor Author

@spren9er spren9er Feb 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I agree.

The code is already updated as it is quite clear, that there will be numerical issues.

duckdb_geomean

Note: DuckDB uses log-based computation for geomean as well (see here).

}

/**
* Generate an expression for calculating argmax over data dimensions.
* As a side effect, this method adds a column to the input *preagg* object
Expand Down
9 changes: 8 additions & 1 deletion packages/core/test/preaggregator.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { Query, add, argmax, argmin, avg, corr, count, covarPop, covariance, gt, isNotDistinct, literal, loadObjects, max, min, product, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSXX, regrSXY, regrSYY, regrSlope, stddev, stddevPop, sum, varPop, variance } from '@uwdata/mosaic-sql';
import { Query, add, argmax, argmin, avg, corr, count, covarPop, covariance, geomean, gt, isNotDistinct, literal, loadObjects, max, min, product, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSXX, regrSXY, regrSYY, regrSlope, stddev, stddevPop, sum, varPop, variance } from '@uwdata/mosaic-sql';
import { Coordinator, Selection } from '../src/index.js';
import { nodeConnector } from './util/node-connector.js';
import { TestClient } from './util/test-client.js';
Expand Down Expand Up @@ -61,6 +61,13 @@ describe('PreAggregator', () => {
expect(await run(avg('x'))).toStrictEqual([3.5, true]);
});

it('supports geomean aggregate', async () => {
const [result, optimized] = await run(geomean('x'));

expect(result).toBeCloseTo(Math.pow(12, 1 / 2), 10);
expect(optimized).toBe(true);
});

it('supports min aggregate', async () => {
expect(await run(min('x'))).toStrictEqual([3, true]);
});
Expand Down
1 change: 1 addition & 0 deletions packages/spec/src/config/transforms.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export function transformNames(overrides = []) {
'dateMonthDay',
'dateDay',
'first',
'geomean',
'geojson',
'last',
'max',
Expand Down
8 changes: 8 additions & 0 deletions packages/spec/src/spec/Transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,14 @@ export interface First extends AggregateOptions, WindowOptions {
first: Arg1;
}

/* A geometric mean aggregate transform. */
export interface Geomean extends AggregateOptions, WindowOptions {
/**
* Compute the geometric mean value of the given column.
*/
geomean: Arg1;
}

/* A last aggregate transform. */
export interface Last extends AggregateOptions, WindowOptions {
/**
Expand Down
9 changes: 9 additions & 0 deletions packages/sql/src/functions/aggregate.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ export function first(expr) {
return aggFn('first', expr);
}

/**
* Compute a geomean aggregate.
* @param {import('../types.js').ExprValue} expr The expression to aggregate.
* @returns {AggregateNode} A SQL aggregate function call.
*/
export function geomean(expr) {
return aggFn('geomean', expr);
}

/**
* Compute a sample kurtosis aggregate.
* @param {import('../types.js').ExprValue} expr The expression to aggregate.
Expand Down
2 changes: 1 addition & 1 deletion packages/sql/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export { VerbatimNode } from './ast/verbatim.js';
export { WindowClauseNode, WindowDefNode, WindowFrameNode, WindowFunctionNode, WindowNode } from './ast/window.js';
export { WithClauseNode } from './ast/with.js';

export { argmax, argmin, arrayAgg, avg, corr, count, covariance, covarPop, entropy, first, kurtosis, mad, max, median, min, mode, last, product, quantile, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSXX, regrSXY, regrSYY, regrSlope, skewness, stddev, stddevPop, stringAgg, sum, variance, varPop } from './functions/aggregate.js';
export { argmax, argmin, arrayAgg, avg, corr, count, covariance, covarPop, entropy, first, geomean, kurtosis, mad, max, median, min, mode, last, product, quantile, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSXX, regrSXY, regrSYY, regrSlope, skewness, stddev, stddevPop, stringAgg, sum, variance, varPop } from './functions/aggregate.js';
export { cond } from './functions/case.js';
export { cast, float32, float64, int32 } from './functions/cast.js';
export { column } from './functions/column.js';
Expand Down
6 changes: 5 additions & 1 deletion packages/sql/test/aggregate.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, describe, it } from 'vitest';
import { columns } from './util/columns.js';
import { argmax, argmin, arrayAgg, avg, column, corr, count, covariance, covarPop, entropy, first, gt, kurtosis, last, mad, max, median, min, mode, product, quantile, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSlope, regrSXX, regrSXY, regrSYY, skewness, stddev, stddevPop, stringAgg, sum, variance, varPop } from '../src/index.js';
import { argmax, argmin, arrayAgg, avg, column, corr, count, covariance, covarPop, entropy, first, geomean, gt, kurtosis, last, mad, max, median, min, mode, product, quantile, regrAvgX, regrAvgY, regrCount, regrIntercept, regrR2, regrSlope, regrSXX, regrSXY, regrSYY, skewness, stddev, stddevPop, stringAgg, sum, variance, varPop } from '../src/index.js';

describe('Aggregate functions', () => {
it('include accessible metadata', () => {
Expand Down Expand Up @@ -63,6 +63,10 @@ describe('Aggregate functions', () => {
expect(String(first('foo'))).toBe('first("foo")');
});

it('include geomean', () => {
expect(String(geomean('foo'))).toBe('geomean("foo")');
});

it('include kurtosis', () => {
expect(String(kurtosis('foo'))).toBe('kurtosis("foo")');
});
Expand Down
1 change: 1 addition & 0 deletions packages/vgplot/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export {
covarPop,
entropy,
first,
geomean,
kurtosis,
mad,
max,
Expand Down