miller/test/input/window.mlr
John Kerl 77811a4788
Sliding window averages (#894)
* todo

* Neaten existing DSL sketch

* rebase on #893, and sketch

* code-complete

* build artifacts for previous commit

* replace - with _ in shift and slwin
2022-01-23 23:03:46 -05:00

56 lines
1.4 KiB
Text

# ================================================================
# Sliding average with window over n previous rows and current row.
# ================================================================
begin {
# INPUT PARAMETERS
# They can do 'mlr put -s window_size=4 -s input_field_names=x,y ...'
if (is_absent(@window_size)) {
@window_size = 3;
}
# In Miller 6 (Go port) we'll have arrays and you'll be able to do
# @input_field_names = ["x", "y"].
if (is_absent(@input_field_names)) {
@input_field_names = splitax("x,y", ",")
} else {
@input_field_names = splitax(@input_field_names, ",")
}
# INITIALIZATION
@output_field_names = {};
for (name in @input_field_names) {
@output_field_names[name] = name . "_avg";
}
for (name in @input_field_names) {
for (i = 0; i < @window_size; i+=1) {
@windows[name][i] = 0;
}
}
# dump;
}
# Slide the windows
for (name in @input_field_names) {
for (i = 1; i < @window_size; i+=1) {
@windows[name][i-1] = @windows[name][i];
}
}
# Update the windows with new data
for (name in @input_field_names) {
@windows[name][@window_size - 1] = $[name];
}
# Compute the averages
sums = {};
for (name in @input_field_names) {
for (i = 0; i < @window_size; i+=1) {
sums[name] += @windows[name][i];
}
}
denominator = @window_size;
if (NR < @window_size) {
denominator = NR
}
for (name in @input_field_names) {
$[@output_field_names[name]] = sums[name] / denominator;
}