forked from influxdata/flux
/
triple_exponential_derivative.go
347 lines (286 loc) · 10.6 KB
/
triple_exponential_derivative.go
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package universe
import (
"math"
"github.com/InfluxCommunity/flux"
"github.com/InfluxCommunity/flux/array"
"github.com/InfluxCommunity/flux/arrow"
"github.com/InfluxCommunity/flux/codes"
"github.com/InfluxCommunity/flux/execute"
"github.com/InfluxCommunity/flux/internal/errors"
"github.com/InfluxCommunity/flux/internal/moving_average"
"github.com/InfluxCommunity/flux/memory"
"github.com/InfluxCommunity/flux/plan"
"github.com/InfluxCommunity/flux/runtime"
"github.com/InfluxCommunity/flux/values"
)
const TripleExponentialDerivativeKind = "tripleExponentialDerivative"
type TripleExponentialDerivativeOpSpec struct {
N int64 `json:"n"`
}
func init() {
tripleExponentialDerivativeSignature := runtime.MustLookupBuiltinType("universe", "tripleExponentialDerivative")
runtime.RegisterPackageValue("universe", TripleExponentialDerivativeKind, flux.MustValue(flux.FunctionValue(TripleExponentialDerivativeKind, createTripleExponentialDerivativeOpSpec, tripleExponentialDerivativeSignature)))
plan.RegisterProcedureSpec(TripleExponentialDerivativeKind, newTripleExponentialDerivativeProcedure, TripleExponentialDerivativeKind)
execute.RegisterTransformation(TripleExponentialDerivativeKind, createTripleExponentialDerivativeTransformation)
}
func createTripleExponentialDerivativeOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
spec := new(TripleExponentialDerivativeOpSpec)
if n, err := args.GetRequiredInt("n"); err != nil {
return nil, err
} else if n <= 0 {
return nil, errors.Newf(codes.Internal, "cannot take triple exponential derivative with a period of %v (must be greater than 0)", n)
} else {
spec.N = n
}
return spec, nil
}
func (s *TripleExponentialDerivativeOpSpec) Kind() flux.OperationKind {
return TripleExponentialDerivativeKind
}
type TripleExponentialDerivativeProcedureSpec struct {
plan.DefaultCost
N int64 `json:"n"`
}
func newTripleExponentialDerivativeProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) {
spec, ok := qs.(*TripleExponentialDerivativeOpSpec)
if !ok {
return nil, errors.Newf(codes.Internal, "invalid spec type %T", qs)
}
return &TripleExponentialDerivativeProcedureSpec{
N: spec.N,
}, nil
}
func (s *TripleExponentialDerivativeProcedureSpec) Kind() plan.ProcedureKind {
return TripleExponentialDerivativeKind
}
func (s *TripleExponentialDerivativeProcedureSpec) Copy() plan.ProcedureSpec {
ns := new(TripleExponentialDerivativeProcedureSpec)
*ns = *s
return ns
}
// TriggerSpec implements plan.TriggerAwareProcedureSpec
func (s *TripleExponentialDerivativeProcedureSpec) TriggerSpec() plan.TriggerSpec {
return plan.NarrowTransformationTriggerSpec{}
}
func createTripleExponentialDerivativeTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*TripleExponentialDerivativeProcedureSpec)
if !ok {
return nil, nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
alloc := a.Allocator()
cache := execute.NewTableBuilderCache(alloc)
d := execute.NewDataset(id, mode, cache)
t := NewTripleExponentialDerivativeTransformation(d, cache, alloc, s)
return t, d, nil
}
type tripleExponentialDerivativeTransformation struct {
execute.ExecutionNode
d execute.Dataset
cache execute.TableBuilderCache
alloc memory.Allocator
i []int
lastVal []interface{}
ema1, ema2, ema3 *moving_average.ExponentialMovingAverage
n int64
}
func NewTripleExponentialDerivativeTransformation(d execute.Dataset, cache execute.TableBuilderCache, alloc memory.Allocator, spec *TripleExponentialDerivativeProcedureSpec) *tripleExponentialDerivativeTransformation {
return &tripleExponentialDerivativeTransformation{
d: d,
cache: cache,
alloc: alloc,
n: spec.N,
}
}
func (t *tripleExponentialDerivativeTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func (t *tripleExponentialDerivativeTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
builder, created := t.cache.TableBuilder(tbl.Key())
if !created {
return errors.Newf(codes.FailedPrecondition, "triple exponential derivative found duplicate table with key: %v", tbl.Key())
}
cols := tbl.Cols()
valueIdx := execute.ColIdx(execute.DefaultValueColLabel, cols)
if valueIdx == -1 {
return errors.New(codes.FailedPrecondition, "cannot find _value column")
}
valueCol := cols[valueIdx]
if valueCol.Type != flux.TInt && valueCol.Type != flux.TUInt && valueCol.Type != flux.TFloat {
return errors.Newf(codes.FailedPrecondition, "cannot take exponential moving average of column %s (type %s)", valueCol.Label, valueCol.Type.String())
}
for j, c := range cols {
if j == valueIdx {
_, err := builder.AddCol(flux.ColMeta{Label: c.Label, Type: flux.TFloat})
if err != nil {
return err
}
} else {
_, err := builder.AddCol(c)
if err != nil {
return err
}
}
}
// Keeps track of current position and last value looked at for columns that are passed through
// Faster than calling ema.PassThrough three times
t.i = make([]int, len(cols))
t.lastVal = make([]interface{}, len(cols))
t.ema1 = moving_average.New(int(t.n), len(cols))
t.ema2 = moving_average.New(int(t.n), len(cols))
t.ema3 = moving_average.New(int(t.n), len(cols))
if err := tbl.Do(func(cr flux.ColReader) error {
if cr.Len() == 0 {
return nil
}
for j, c := range cr.Cols() {
isValueCol := valueIdx == j
var err error
switch c.Type {
case flux.TBool:
// We can pass through values using one of the EMAs, since the same number of values have to be appended
err = t.passThrough(moving_average.NewArrayContainer(cr.Bools(j)), builder, j)
case flux.TInt:
err = t.doFirstEMA(moving_average.NewArrayContainer(cr.Ints(j)), builder, j, isValueCol)
case flux.TUInt:
err = t.doFirstEMA(moving_average.NewArrayContainer(cr.UInts(j)), builder, j, isValueCol)
case flux.TFloat:
err = t.doFirstEMA(moving_average.NewArrayContainer(cr.Floats(j)), builder, j, isValueCol)
case flux.TString:
err = t.passThrough(moving_average.NewArrayContainer(cr.Strings(j)), builder, j)
case flux.TTime:
err = t.passThroughTime(cr.Times(j), builder, j)
}
if err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
for j := range cols {
if j == valueIdx {
if err := t.doRest(builder, j); err != nil {
return err
}
} else {
// Check for any incomplete TRIXs, append the last value
if int64(t.i[j]) < 3*(t.n-1) {
val := values.New(t.lastVal[j])
if err := builder.AppendValue(j, val); err != nil {
return err
}
}
}
}
return nil
}
func (t *tripleExponentialDerivativeTransformation) passThrough(vs *moving_average.ArrayContainer, b execute.TableBuilder, bj int) error {
// Skip all values which Triple Exponential Derivative won't output
// - math.Min decides whether to skip all the values in the slice
// - math.Max leaves the index unchanged if we want to pass through all the values in the slice (since math.Min would return a negative)
j := int(math.Max(0, math.Min(float64(vs.Len()), float64(3*(t.n-1))-float64(t.i[bj])+1)))
t.i[bj] += int(math.Max(0, math.Min(float64(vs.Len()), float64(3*(t.n-1))-float64(t.i[bj])+1)))
if j < vs.Len() {
slice := vs.Slice(j, vs.Len()).Array()
defer slice.Release()
switch s := slice.(type) {
case *array.Boolean:
if err := b.AppendBools(bj, s); err != nil {
return err
}
case *array.String:
if err := b.AppendStrings(bj, s); err != nil {
return err
}
}
}
t.lastVal[bj] = vs.Value(vs.Len() - 1)
return nil
}
func (t *tripleExponentialDerivativeTransformation) passThroughTime(vs *array.Int, b execute.TableBuilder, bj int) error {
// Skip all values which Triple Exponential Derivative won't output
// - math.Min decides whether to skip all the values in the slice
// - math.Max leaves the index unchanged if we want to pass through all the values in the slice (since math.Min would return a negative)
j := int(math.Max(0, math.Min(float64(vs.Len()), float64(3*(t.n-1))-float64(t.i[bj])+1)))
t.i[bj] += int(math.Max(0, math.Min(float64(vs.Len()), float64(3*(t.n-1))-float64(t.i[bj])+1)))
if j < vs.Len() {
slice := arrow.IntSlice(vs, j, vs.Len())
defer slice.Release()
if err := b.AppendTimes(bj, slice); err != nil {
return err
}
}
t.lastVal[bj] = execute.Time(vs.Value(vs.Len() - 1))
return nil
}
func (t *tripleExponentialDerivativeTransformation) doFirstEMA(vs *moving_average.ArrayContainer, b execute.TableBuilder, bj int, doDEMA bool) error {
// if !doDEMA, append the last 2n - 1 values
if !doDEMA {
return t.passThrough(vs, b, bj)
}
return t.ema1.DoNumeric(vs, b, bj, doDEMA, false)
}
func (t *tripleExponentialDerivativeTransformation) doRest(b execute.TableBuilder, bj int) error {
firstEMA := t.ema1.GetEMA(bj)
// Convert firstEMA to *array.Float64
arr1 := arrayToFloatArrow(firstEMA, t.alloc)
defer arr1.Release()
// Do the second EMA
if err := t.ema2.DoNumeric(moving_average.NewArrayContainer(arr1), b, bj, true, false); err != nil {
return err
}
// Get the second EMA
secondEMA := t.ema2.GetEMA(bj)
arr2 := arrayToFloatArrow(secondEMA, t.alloc)
defer arr2.Release()
// Get the third EMA
if err := t.ema3.DoNumeric(moving_average.NewArrayContainer(arr2), b, bj, true, false); err != nil {
return err
}
thirdEMA := t.ema3.GetEMA(bj)
// If there weren't enough values to take 2 EMAs, append a null
if thirdEMA == nil {
if err := b.AppendNil(bj); err != nil {
return nil
}
} else {
for i := 1; i < len(thirdEMA); i++ {
if thirdEMA[i] == nil || thirdEMA[i-1] == nil {
if err := b.AppendNil(bj); err != nil {
return err
}
} else {
val := ((thirdEMA[i].(float64) / thirdEMA[i-1].(float64)) - 1) * 100
if err := b.AppendFloat(bj, val); err != nil {
return err
}
}
}
}
return nil
}
func (t *tripleExponentialDerivativeTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error {
return t.d.UpdateWatermark(mark)
}
func (t *tripleExponentialDerivativeTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *tripleExponentialDerivativeTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}
func arrayToFloatArrow(a []interface{}, alloc memory.Allocator) *array.Float {
bld := arrow.NewFloatBuilder(alloc)
defer bld.Release()
for _, val := range a {
if val != nil {
bld.Append(val.(float64))
} else {
bld.AppendNull()
}
}
return bld.NewFloatArray()
}