forked from elastic/kibana
/
moving_average.tsx
286 lines (269 loc) · 8.94 KB
/
moving_average.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import React, { useState } from 'react';
import { EuiFieldNumber, EuiFormRow } from '@elastic/eui';
import { FormattedIndexPatternColumn, ReferenceBasedIndexPatternColumn } from '../column_types';
import { IndexPatternLayer } from '../../../types';
import {
buildLabelFunction,
checkForDateHistogram,
getErrorsForDateReference,
dateBasedOperationToExpression,
hasDateField,
} from './utils';
import { updateColumnParam } from '../../layer_helpers';
import {
getFormatFromPreviousColumn,
isValidNumber,
useDebounceWithOptions,
getFilter,
} from '../helpers';
import { adjustTimeScaleOnOtherColumnChange } from '../../time_scale_utils';
import { HelpPopover, HelpPopoverButton } from '../../../help_popover';
import type { OperationDefinition, ParamEditorProps } from '..';
const ofName = buildLabelFunction((name?: string) => {
return i18n.translate('xpack.lens.indexPattern.movingAverageOf', {
defaultMessage: 'Moving average of {name}',
values: {
name:
name ??
i18n.translate('xpack.lens.indexPattern.incompleteOperation', {
defaultMessage: '(incomplete)',
}),
},
});
});
const WINDOW_DEFAULT_VALUE = 5;
export type MovingAverageIndexPatternColumn = FormattedIndexPatternColumn &
ReferenceBasedIndexPatternColumn & {
operationType: 'moving_average';
params: {
window: number;
};
};
export const movingAverageOperation: OperationDefinition<
MovingAverageIndexPatternColumn,
'fullReference'
> = {
type: 'moving_average',
priority: 1,
displayName: i18n.translate('xpack.lens.indexPattern.movingAverage', {
defaultMessage: 'Moving average',
}),
input: 'fullReference',
selectionStyle: 'full',
requiredReferences: [
{
input: ['field', 'managedReference'],
validateMetadata: (meta) => meta.dataType === 'number' && !meta.isBucketed,
},
],
operationParams: [
{ name: 'window', type: 'number', required: false, defaultValue: WINDOW_DEFAULT_VALUE },
],
getPossibleOperation: (indexPattern) => {
if (hasDateField(indexPattern)) {
return {
dataType: 'number',
isBucketed: false,
scale: 'ratio',
};
}
},
getDefaultLabel: (column, indexPattern, columns) => {
return ofName(columns[column.references[0]]?.label, column.timeScale);
},
toExpression: (layer, columnId) => {
return dateBasedOperationToExpression(layer, columnId, 'moving_average', {
window: [(layer.columns[columnId] as MovingAverageIndexPatternColumn).params.window],
});
},
buildColumn: (
{ referenceIds, previousColumn, layer },
columnParams = { window: WINDOW_DEFAULT_VALUE }
) => {
const metric = layer.columns[referenceIds[0]];
const { window = WINDOW_DEFAULT_VALUE } = columnParams;
return {
label: ofName(metric?.label, previousColumn?.timeScale),
dataType: 'number',
operationType: 'moving_average',
isBucketed: false,
scale: 'ratio',
references: referenceIds,
timeScale: previousColumn?.timeScale,
filter: getFilter(previousColumn, columnParams),
params: {
window,
...getFormatFromPreviousColumn(previousColumn),
},
};
},
paramEditor: MovingAverageParamEditor,
isTransferable: (column, newIndexPattern) => {
return hasDateField(newIndexPattern);
},
onOtherColumnChanged: adjustTimeScaleOnOtherColumnChange,
getErrorMessage: (layer: IndexPatternLayer, columnId: string) => {
return getErrorsForDateReference(
layer,
columnId,
i18n.translate('xpack.lens.indexPattern.movingAverage', {
defaultMessage: 'Moving average',
})
);
},
getHelpMessage: () => <MovingAveragePopup />,
getDisabledStatus(indexPattern, layer) {
return checkForDateHistogram(
layer,
i18n.translate('xpack.lens.indexPattern.movingAverage', {
defaultMessage: 'Moving average',
})
)?.join(', ');
},
timeScalingMode: 'optional',
filterable: true,
documentation: {
section: 'calculation',
signature: i18n.translate('xpack.lens.indexPattern.moving_average.signature', {
defaultMessage: 'metric: number, [window]: number',
}),
description: i18n.translate('xpack.lens.indexPattern.movingAverage.documentation', {
defaultMessage: `
Calculates the moving average of a metric over time, averaging the last n-th values to calculate the current value. To use this function, you need to configure a date histogram dimension as well.
The default window value is {defaultValue}.
This calculation will be done separately for separate series defined by filters or top values dimensions.
Takes a named parameter \`window\` which specifies how many last values to include in the average calculation for the current value.
Example: Smooth a line of measurements:
\`moving_average(sum(bytes), window=5)\`
`,
values: {
defaultValue: WINDOW_DEFAULT_VALUE,
},
}),
},
};
function MovingAverageParamEditor({
layer,
updateLayer,
currentColumn,
columnId,
}: ParamEditorProps<MovingAverageIndexPatternColumn>) {
const [inputValue, setInputValue] = useState(String(currentColumn.params.window));
useDebounceWithOptions(
() => {
if (!isValidNumber(inputValue, true, undefined, 1)) return;
const inputNumber = parseInt(inputValue, 10);
updateLayer(
updateColumnParam({
layer,
columnId,
paramName: 'window',
value: inputNumber,
})
);
},
{ skipFirstRender: true },
256,
[inputValue]
);
return (
<EuiFormRow
label={i18n.translate('xpack.lens.indexPattern.movingAverage.window', {
defaultMessage: 'Window size',
})}
display="columnCompressed"
fullWidth
isInvalid={!isValidNumber(inputValue)}
>
<EuiFieldNumber
compressed
value={inputValue}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setInputValue(e.target.value)}
min={1}
step={1}
isInvalid={!isValidNumber(inputValue)}
/>
</EuiFormRow>
);
}
const MovingAveragePopup = () => {
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
return (
<HelpPopover
anchorPosition="upCenter"
button={
<HelpPopoverButton
onClick={() => {
setIsPopoverOpen(!isPopoverOpen);
}}
>
{i18n.translate('xpack.lens.indexPattern.movingAverage.helpText', {
defaultMessage: 'How it works',
})}
</HelpPopoverButton>
}
closePopover={() => setIsPopoverOpen(false)}
isOpen={isPopoverOpen}
title={i18n.translate('xpack.lens.indexPattern.movingAverage.titleHelp', {
defaultMessage: 'How moving average works',
})}
>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.basicExplanation"
defaultMessage="Moving average slides a window across the data and displays the average value. Moving average is supported only by date histograms."
/>
</p>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.longerExplanation"
defaultMessage="To calculate the moving average, Lens uses the mean of the window and applies a skip policy for gaps. For missing values, the bucket is skipped, and the calculation is performed on the next value."
/>
</p>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.tableExplanation"
defaultMessage="For example, given the data [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can calculate a simple moving average with a window size of 5:"
/>
</p>
<ul>
<li>(1 + 2 + 3 + 4 + 5) / 5 = 3</li>
<li>(2 + 3 + 4 + 5 + 6) / 5 = 4</li>
<li>...</li>
<li>(5 + 6 + 7 + 8 + 9) / 5 = 7</li>
</ul>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.windowLimitations"
defaultMessage="The window does not include the current value."
/>
</p>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.windowInitialPartial"
defaultMessage="The window is partial until it reaches the requested number of items. For example, with a window size of 5:"
/>
</p>
<ul>
<li>(1 + 2) / 2 = 1.5</li>
<li>(1 + 2 + 3) / 3 = 2</li>
<li>(1 + 2 + 3 + 4) / 4 = 2.5</li>
<li>(1 + 2 + 3 + 4 + 5) / 5 = 3</li>
</ul>
<p>
<FormattedMessage
id="xpack.lens.indexPattern.movingAverage.limitations"
defaultMessage="The first moving average value starts at the second item."
/>
</p>
</HelpPopover>
);
};