import type { ExprValue, FromExpr } from '../types.js'; import type { ColumnRefNode } from '../ast/column-ref.js'; import { Query } from '../ast/query.js'; import { argmax, argmin, max, min } from '../functions/aggregate.js'; import { int32 } from '../functions/cast.js'; import { list } from '../functions/list.js'; import { floor } from '../functions/numeric.js'; import { unnest } from '../functions/unnest.js'; /** * M4 is an optimization for value-preserving time-series aggregation * (https://www.vldb.org/pvldb/vol7/p797-jugel.pdf). This implementation uses * an efficient version with a single scan and the aggregate functions * argmin and argmax, following https://arxiv.org/pdf/2306.03714.pdf. * This method can bin along either the *x* or *y* dimension, as determined * by the caller-provided *bin* expression. * @param input The base query or table. * @param bin An expression that maps * time-series values to fractional pixel positions. * @param x The x dimension column name. * @param y The y dimension column name. * @param groups Additional groupby columns, for example for faceted charts. * @returns The resulting M4 query. */ export function m4( input: FromExpr, bin: ExprValue, x: string, y: string, groups: ColumnRefNode[] = [] ) { const pixel = int32(floor(bin)); return Query .from(input) .select({ [x]: unnest(list([min(x), max(x), argmin(x, y), argmax(x, y)])), [y]: unnest(list([argmin(y, x), argmax(y, x), min(y), max(y)])) }, groups) .distinct() .groupby(pixel, groups) .orderby(groups, x); }