transforms

package
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregateFunc

type AggregateFunc func(values []float64) float64

AggregateFunc defines how to aggregate numeric values.

var (
	// Sum aggregates by summing all values
	Sum AggregateFunc = func(values []float64) float64 {
		sum := 0.0
		for _, v := range values {
			sum += v
		}
		return sum
	}

	// Mean aggregates by calculating the mean (average)
	Mean AggregateFunc = func(values []float64) float64 {
		if len(values) == 0 {
			return 0
		}
		return Sum(values) / float64(len(values))
	}

	// Max aggregates by taking the maximum value
	Max AggregateFunc = func(values []float64) float64 {
		if len(values) == 0 {
			return 0
		}
		max := values[0]
		for _, v := range values[1:] {
			if v > max {
				max = v
			}
		}
		return max
	}

	// Min aggregates by taking the minimum value
	Min AggregateFunc = func(values []float64) float64 {
		if len(values) == 0 {
			return 0
		}
		min := values[0]
		for _, v := range values[1:] {
			if v < min {
				min = v
			}
		}
		return min
	}

	// Count aggregates by counting the number of values
	Count AggregateFunc = func(values []float64) float64 {
		return float64(len(values))
	}

	// Median aggregates by calculating the median
	Median AggregateFunc = func(values []float64) float64 {
		if len(values) == 0 {
			return 0
		}

		sorted := make([]float64, len(values))
		copy(sorted, values)

		for i := 0; i < len(sorted); i++ {
			for j := i + 1; j < len(sorted); j++ {
				if sorted[i] > sorted[j] {
					sorted[i], sorted[j] = sorted[j], sorted[i]
				}
			}
		}
		mid := len(sorted) / 2
		if len(sorted)%2 == 0 {
			return (sorted[mid-1] + sorted[mid]) / 2
		}
		return sorted[mid]
	}
)

Common aggregation functions

type BinOptions

type BinOptions struct {
	// Thresholds specifies explicit bin edges (overrides Count)
	Thresholds []float64

	// Count specifies the approximate number of bins (default: 10)
	Count int

	// Domain specifies the [min, max] range to bin over
	Domain [2]float64

	// Nice rounds bin edges to nice numbers
	Nice bool
}

BinOptions configures binning behavior

type DataPoint

type DataPoint struct {
	X     interface{} // X value (can be time.Time, float64, string, etc.)
	Y     float64     // Y value (numeric)
	Y0    float64     // Baseline Y value (for stacking)
	Y1    float64     // Top Y value (for stacking)
	Label string      // Category label
	Value float64     // Generic numeric value
	Count int         // Count for aggregations
	Group string      // Group identifier
	Index int         // Original index
	Data  interface{} // Original data reference
}

DataPoint represents a generic data point that can be transformed. Transforms operate on slices of DataPoints and return transformed data.

func ToDataPoints

func ToDataPoints(points []TimeSeriesPoint) []DataPoint

ToDataPoints converts TimeSeriesPoints to DataPoints

type EWM

type EWM struct {
	// contains filtered or unexported fields
}

EWM provides pandas-style exponentially weighted functions

func NewEWM

func NewEWM(alpha float64) *EWM

NewEWM creates a new exponentially weighted operator

func (*EWM) Adjust

func (ewm *EWM) Adjust(adjust bool) *EWM

Adjust sets whether to use adjustment in weights

func (*EWM) IgnoreNA

func (ewm *EWM) IgnoreNA(ignore bool) *EWM

IgnoreNA sets whether to ignore NA values

func (*EWM) Mean

func (ewm *EWM) Mean() Transform

Mean calculates exponentially weighted mean

func (*EWM) MinPeriods

func (ewm *EWM) MinPeriods(n int) *EWM

MinPeriods sets the minimum number of observations

func (*EWM) Std

func (ewm *EWM) Std() Transform

Std calculates exponentially weighted standard deviation

func (*EWM) Var

func (ewm *EWM) Var() Transform

Var calculates exponentially weighted variance

type Expanding

type Expanding struct {
	// contains filtered or unexported fields
}

Expanding provides pandas-style expanding window operations

func NewExpanding

func NewExpanding() *Expanding

NewExpanding creates a new expanding window operator

func (*Expanding) Apply

func (e *Expanding) Apply(fn AggregateFunc) Transform

Apply applies a custom aggregation function

func (*Expanding) Count

func (e *Expanding) Count() Transform

Count calculates expanding count

func (*Expanding) Max

func (e *Expanding) Max() Transform

Max calculates expanding maximum

func (*Expanding) Mean

func (e *Expanding) Mean() Transform

Mean calculates expanding mean

func (*Expanding) Min

func (e *Expanding) Min() Transform

Min calculates expanding minimum

func (*Expanding) MinPeriods

func (e *Expanding) MinPeriods(n int) *Expanding

MinPeriods sets the minimum number of observations required

func (*Expanding) Std

func (e *Expanding) Std() Transform

Std calculates expanding standard deviation

func (*Expanding) Sum

func (e *Expanding) Sum() Transform

Sum calculates expanding sum (cumulative sum)

func (*Expanding) Var

func (e *Expanding) Var() Transform

Var calculates expanding variance

type GroupOptions

type GroupOptions struct {
	// By specifies the field to group by ("X", "Label", "Group")
	By string

	// Aggregate specifies how to aggregate Y values
	Aggregate AggregateFunc

	// Sort specifies whether to sort groups (by key or value)
	Sort string // "key", "value", or ""
}

GroupOptions configures grouping behavior

type HoppingWindow

type HoppingWindow struct {
	Size int // Window size in number of points
	Hop  int // Hop size (step between windows)
}

HoppingWindow creates fixed-size windows with configurable hop/stride

func NewHoppingWindow

func NewHoppingWindow(size, hop int) *HoppingWindow

NewHoppingWindow creates a hopping window strategy

func (*HoppingWindow) WindowBounds

func (hw *HoppingWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a hopping window

func (*HoppingWindow) Windows

func (hw *HoppingWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for hopping windows

type NormalizeOptions

type NormalizeOptions struct {
	// Method specifies normalization method ("percentage", "zscore", "minmax")
	Method string

	// By specifies the field to normalize by ("group", "all")
	By string
}

NormalizeOptions configures normalization behavior

type Rolling

type Rolling struct {
	// contains filtered or unexported fields
}

Rolling provides pandas-style rolling window operations

func NewRolling

func NewRolling(window int) *Rolling

NewRolling creates a new rolling window operator

func (*Rolling) Apply

func (r *Rolling) Apply(fn AggregateFunc) Transform

Apply applies a custom aggregation function

func (*Rolling) Center

func (r *Rolling) Center(center bool) *Rolling

Center centers the window labels

func (*Rolling) Kurt

func (r *Rolling) Kurt() Transform

Kurt calculates rolling kurtosis

func (*Rolling) Max

func (r *Rolling) Max() Transform

Max calculates rolling maximum

func (*Rolling) Mean

func (r *Rolling) Mean() Transform

Mean calculates rolling mean

func (*Rolling) Median

func (r *Rolling) Median() Transform

Median calculates rolling median

func (*Rolling) Min

func (r *Rolling) Min() Transform

Min calculates rolling minimum

func (*Rolling) MinPeriods

func (r *Rolling) MinPeriods(n int) *Rolling

MinPeriods sets the minimum number of observations required

func (*Rolling) Quantile

func (r *Rolling) Quantile(q float64) Transform

Quantile calculates rolling quantile

func (*Rolling) Skew

func (r *Rolling) Skew() Transform

Skew calculates rolling skewness

func (*Rolling) Std

func (r *Rolling) Std() Transform

Std calculates rolling standard deviation

func (*Rolling) Sum

func (r *Rolling) Sum() Transform

Sum calculates rolling sum

func (*Rolling) Var

func (r *Rolling) Var() Transform

Var calculates rolling variance

type SessionWindow

type SessionWindow struct {
	GapThreshold time.Duration // Maximum gap between points in the same session
}

SessionWindow groups points based on gaps in time

func NewSessionWindow

func NewSessionWindow(gapThreshold time.Duration) *SessionWindow

NewSessionWindow creates a session window strategy

func (*SessionWindow) WindowBounds

func (sw *SessionWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a session window

func (*SessionWindow) Windows

func (sw *SessionWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for session windows

type SlidingWindow

type SlidingWindow struct {
	Size int // Window size in number of points
	Step int // Step size (default: 1 for maximum overlap)
}

SlidingWindow creates overlapping windows of fixed size

func NewSlidingWindow

func NewSlidingWindow(size int) *SlidingWindow

NewSlidingWindow creates a sliding window strategy

func (*SlidingWindow) WindowBounds

func (sw *SlidingWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a window

func (*SlidingWindow) Windows

func (sw *SlidingWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for sliding windows

func (*SlidingWindow) WithStep

func (sw *SlidingWindow) WithStep(step int) *SlidingWindow

WithStep sets the step size for sliding windows

type SmoothOptions

type SmoothOptions struct {
	// Method specifies the smoothing method ("movingAverage", "loess", "exponential")
	Method string

	// WindowSize specifies the window size for moving averages
	WindowSize int

	// Bandwidth specifies the bandwidth for LOESS smoothing (0-1)
	Bandwidth float64

	// Alpha specifies the smoothing factor for exponential smoothing (0-1)
	Alpha float64
}

SmoothOptions configures smoothing behavior

type SnapshotWindow

type SnapshotWindow struct{}

SnapshotWindow groups events that occur at the exact same timestamp Unlike other windows, snapshot windows are event-driven and fire on every event

func NewSnapshotWindow

func NewSnapshotWindow() *SnapshotWindow

NewSnapshotWindow creates a snapshot window strategy

func (*SnapshotWindow) WindowBounds

func (sw *SnapshotWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a snapshot window

func (*SnapshotWindow) Windows

func (sw *SnapshotWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for snapshot windows Each unique timestamp gets its own window

type StackOptions

type StackOptions struct {
	// By specifies the field to group by for stacking
	By string

	// Order specifies the stacking order ("ascending", "descending", "none")
	Order string

	// Offset specifies the baseline ("zero", "center", "normalize")
	Offset string
}

StackOptions configures stacking behavior

type TimeSeriesPoint

type TimeSeriesPoint struct {
	Time  time.Time
	Value float64
	Label string
}

TimeSeriesPoint represents a time-series data point

func FromDataPoints

func FromDataPoints(points []DataPoint) []TimeSeriesPoint

FromDataPoints converts DataPoints back to TimeSeriesPoints

type TimeWindow

type TimeWindow struct {
	Interval time.Duration // Time interval for each window
}

TimeWindow partitions data by fixed time intervals

func NewTimeWindow

func NewTimeWindow(interval time.Duration) *TimeWindow

NewTimeWindow creates a time-based window strategy

func (*TimeWindow) WindowBounds

func (tw *TimeWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a time window

func (*TimeWindow) Windows

func (tw *TimeWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for time-based windows

type Transform

type Transform func([]DataPoint) []DataPoint

Transform is a function that transforms a slice of data points.

func Abs

func Abs() Transform

Abs converts all Y values to their absolute values

func ApplyWindow

func ApplyWindow(strategy WindowStrategy, fn AggregateFunc) Transform

ApplyWindow applies a window strategy and aggregates each window

func Bin

func Bin(opts BinOptions) Transform

Bin creates a binning transform that groups continuous data into discrete bins. Useful for creating histograms and frequency distributions.

Example:

data := []DataPoint{{Y: 1.5}, {Y: 2.3}, {Y: 5.7}, {Y: 8.1}}
binned := Bin(BinOptions{Count: 3})(data)
// Results in 3 bins with counts

func BinCount

func BinCount(binSize float64) Transform

BinCount creates a simple frequency count binning transform

func Clamp

func Clamp(min, max float64) Transform

Clamp restricts values to a specified range

func Cumulative

func Cumulative() Transform

Cumulative creates a cumulative sum transform

func Dodge

func Dodge(by string, padding float64) Transform

Dodge creates side-by-side positioning for grouped bars Instead of stacking, places items next to each other

func Downsample

func Downsample(n int) Transform

Downsample reduces the number of points by sampling every nth point

func Expand

func Expand() Transform

Expand expands stacked values to fill the entire range

func ExponentialSmoothing

func ExponentialSmoothing(alpha float64) Transform

ExponentialSmoothing applies exponential smoothing

func Filter

func Filter(predicate func(DataPoint) bool) Transform

Filter creates a transform that filters data points based on a predicate

func GroupBy

func GroupBy(opts GroupOptions) Transform

GroupBy creates a grouping transform that aggregates data by a field. Useful for creating summary statistics grouped by category.

Example:

data := []DataPoint{
  {Label: "A", Y: 10},
  {Label: "A", Y: 20},
  {Label: "B", Y: 15},
}
grouped := GroupBy(GroupOptions{By: "Label", Aggregate: Sum})(data)
// Results in: [{Label: "A", Y: 30}, {Label: "B", Y: 15}]

func Histogram

func Histogram(thresholds ...float64) Transform

Histogram is an alias for Bin with sensible defaults

func Interpolate

func Interpolate() Transform

Interpolate fills in missing values using linear interpolation

func Loess

func Loess(bandwidth float64) Transform

Loess applies LOESS (Locally Estimated Scatterplot Smoothing) This is a simplified version of LOESS

func Log

func Log(base float64) Transform

Log applies logarithmic transformation

func Map

func Map(fn func(DataPoint) DataPoint) Transform

Map creates a transform that maps each data point through a function

func MovingAverage

func MovingAverage(windowSize int) Transform

MovingAverage creates a simple moving average transform

func Normalize

func Normalize(opts NormalizeOptions) Transform

Normalize creates a normalization transform that scales values to a standard range. Useful for comparing datasets with different scales or creating percentage-based views.

Example:

data := []DataPoint{{Y: 10}, {Y: 20}, {Y: 30}}
normalized := Normalize(NormalizeOptions{Method: "percentage"})(data)
// Results in percentage of total: [16.67%, 33.33%, 50%]

func NormalizeByGroup

func NormalizeByGroup(groupBy string, method string) Transform

NormalizeByGroup normalizes within each group

func NormalizeFraction

func NormalizeFraction() Transform

NormalizeFraction converts values to fractions of the total (0-1)

func NormalizeMinMax

func NormalizeMinMax(targetMin, targetMax float64) Transform

NormalizeMinMax scales values to a specified range [min, max]

func NormalizePercentage

func NormalizePercentage() Transform

NormalizePercentage converts values to percentages of the total

func NormalizeZScore

func NormalizeZScore() Transform

NormalizeZScore converts values to z-scores (standard scores)

func Offset

func Offset(amount float64) Transform

Offset adds a constant to all Y values

func Percentile

func Percentile(p float64) Transform

Percentile calculates percentiles for the Y values

func Reduce

func Reduce(fn AggregateFunc) Transform

Reduce aggregates all data points into a single value using the given function

func SavitzkyGolay

func SavitzkyGolay(windowSize, polyOrder int) Transform

SavitzkyGolay applies Savitzky-Golay smoothing (simplified)

func Scale

func Scale(factor float64) Transform

Scale multiplies all Y values by a constant

func Smooth

func Smooth(opts SmoothOptions) Transform

Smooth creates a smoothing transform that applies various smoothing algorithms. Useful for trend lines, noise reduction, and pattern identification.

Example:

data := []DataPoint{{Y: 1}, {Y: 5}, {Y: 2}, {Y: 8}, {Y: 3}}
smoothed := Smooth(SmoothOptions{Method: "movingAverage", WindowSize: 3})(data)

func SnapshotAggregate

func SnapshotAggregate(fn AggregateFunc) Transform

SnapshotAggregate creates a snapshot window aggregation transform

func SnapshotCount

func SnapshotCount() Transform

SnapshotCount creates a snapshot window count transform

func SnapshotMax

func SnapshotMax() Transform

SnapshotMax creates a snapshot window max transform

func SnapshotMean

func SnapshotMean() Transform

SnapshotMean creates a snapshot window mean transform

func SnapshotMin

func SnapshotMin() Transform

SnapshotMin creates a snapshot window min transform

func SnapshotSum

func SnapshotSum() Transform

SnapshotSum creates a snapshot window sum transform

func Sort

func Sort(by string, ascending bool) Transform

Sort creates a transform that sorts data points

func Sqrt

func Sqrt() Transform

Sqrt applies square root transformation

func Stack

func Stack(opts StackOptions) Transform

Stack creates a stacking transform that computes Y0 and Y1 for stacked visualizations. Essential for stacked bar charts, area charts, and stream graphs.

Example:

data := []DataPoint{
  {Label: "2020", Group: "A", Y: 10},
  {Label: "2020", Group: "B", Y: 15},
  {Label: "2021", Group: "A", Y: 12},
  {Label: "2021", Group: "B", Y: 18},
}
stacked := Stack(StackOptions{By: "Label"})(data)
// Results in Y0 and Y1 computed for stacking

func StackCenter

func StackCenter(by string) Transform

StackCenter creates a centered (diverging) stack

func StackNormalize

func StackNormalize(by string) Transform

StackNormalize creates a normalized (100%) stack

func StackZero

func StackZero(by string) Transform

StackZero is a convenience function for zero-baseline stacking

func Top

func Top(n int) Transform

Top returns the top N data points by value

func Unstack

func Unstack() Transform

Unstack reverses stacking by resetting Y0 and Y1

func WeightedMovingAverage

func WeightedMovingAverage(weights []float64) Transform

WeightedMovingAverage applies weighted moving average with custom weights

func Window

func Window(size int, fn AggregateFunc) Transform

Window applies a windowed aggregation (rolling window)

func WindowAggregate

func WindowAggregate(size int, fn AggregateFunc, strategy string) Transform

WindowAggregate creates a windowed aggregation transform

func WindowedMax

func WindowedMax(size int, strategy string) Transform

WindowedMax creates a windowed max transform

func WindowedMean

func WindowedMean(size int, strategy string) Transform

WindowedMean creates a windowed mean transform

func WindowedMin

func WindowedMin(size int, strategy string) Transform

WindowedMin creates a windowed min transform

func WindowedSum

func WindowedSum(size int, strategy string) Transform

WindowedSum creates a windowed sum transform

type TumblingWindow

type TumblingWindow struct {
	Size int // Window size in number of points
}

TumblingWindow creates non-overlapping windows of fixed size

func NewTumblingWindow

func NewTumblingWindow(size int) *TumblingWindow

NewTumblingWindow creates a tumbling window strategy

func (*TumblingWindow) WindowBounds

func (tw *TumblingWindow) WindowBounds(windowID int, data []DataPoint) (start, end int)

WindowBounds returns the bounds for a tumbling window

func (*TumblingWindow) Windows

func (tw *TumblingWindow) Windows(data []DataPoint) [][]int

Windows returns window assignments for tumbling windows

type WindowStrategy

type WindowStrategy interface {
	// Windows returns the window assignments for each data point
	// Returns a slice of window IDs for each input point
	Windows(data []DataPoint) [][]int

	// WindowBounds returns the start and end indices for a window ID
	WindowBounds(windowID int, data []DataPoint) (start, end int)
}

WindowStrategy defines how to partition data into windows

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL