-
Notifications
You must be signed in to change notification settings - Fork 25
/
ema.go
205 lines (182 loc) · 6.29 KB
/
ema.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
package components
import (
"errors"
"math"
"go.uber.org/fx"
policylangv1 "github.com/fluxninja/aperture/api/gen/proto/go/aperture/policy/language/v1"
"github.com/fluxninja/aperture/pkg/config"
"github.com/fluxninja/aperture/pkg/notifiers"
"github.com/fluxninja/aperture/pkg/policies/controlplane/constraints"
"github.com/fluxninja/aperture/pkg/policies/controlplane/iface"
"github.com/fluxninja/aperture/pkg/policies/controlplane/runtime"
)
type stage int
const (
warmUpStage stage = iota
emaStage
)
// EMA is an Exponential Moving Average filter.
type EMA struct {
lastGoodOutput runtime.Reading
policyReadAPI iface.Policy
// The smoothing factor between 0-1. A higher value discounts older observations faster.
alpha float64
sum float64
count float64
// The correction factor on the maximum relative to the signal
correctionFactorOnMaxViolation float64
// The correction factor on the minimum relative to the signal
correctionFactorOnMinViolation float64
currentStage stage
// The initial value of EMA is the average of the first warm_up_window number of observations.
warmupWindow uint32
emaWindow uint32
warmupCount uint32
invalidCount uint32
validDuringWarmup bool
}
// Name implements runtime.Component.
func (*EMA) Name() string { return "EMA" }
// Type implements runtime.Component.
func (*EMA) Type() runtime.ComponentType { return runtime.ComponentTypeSignalProcessor }
// Make sure EMA complies with Component interface.
var _ runtime.Component = (*EMA)(nil)
// NewEMAAndOptions returns a new EMA filter and its Fx options.
func NewEMAAndOptions(emaProto *policylangv1.EMA,
_ int,
policyReadAPI iface.Policy,
) (*EMA, fx.Option, error) {
// period of tick
evaluationPeriod := policyReadAPI.GetEvaluationInterval()
// number of ticks in emaWindow
emaWindow := math.Ceil(float64(emaProto.EmaWindow.AsDuration()) / float64(evaluationPeriod))
alpha := 2.0 / (emaWindow + 1)
warmUpWindow := uint32(math.Ceil(float64(emaProto.WarmUpWindow.AsDuration()) / float64(evaluationPeriod)))
ema := &EMA{
correctionFactorOnMinViolation: emaProto.CorrectionFactorOnMinEnvelopeViolation,
correctionFactorOnMaxViolation: emaProto.CorrectionFactorOnMaxEnvelopeViolation,
alpha: alpha,
warmupWindow: warmUpWindow,
emaWindow: uint32(emaWindow),
policyReadAPI: policyReadAPI,
validDuringWarmup: emaProto.ValidDuringWarmup,
}
ema.resetStages()
return ema, fx.Options(), nil
}
func (ema *EMA) resetStages() {
ema.currentStage = warmUpStage
ema.warmupCount = 0
ema.invalidCount = 0
ema.sum = 0
ema.count = 0
ema.lastGoodOutput = runtime.InvalidReading()
}
// Execute implements runtime.Component.Execute.
func (ema *EMA) Execute(inPortReadings runtime.PortToValue, tickInfo runtime.TickInfo) (runtime.PortToValue, error) {
logger := ema.policyReadAPI.GetStatusRegistry().GetLogger()
retErr := func(err error) (runtime.PortToValue, error) {
return runtime.PortToValue{
"output": []runtime.Reading{runtime.InvalidReading()},
}, err
}
input := inPortReadings.ReadSingleValuePort("input")
maxEnvelope := inPortReadings.ReadSingleValuePort("max_envelope")
minEnvelope := inPortReadings.ReadSingleValuePort("min_envelope")
output := runtime.InvalidReading()
switch ema.currentStage {
case warmUpStage:
ema.warmupCount++
if input.Valid() {
ema.sum += input.Value()
ema.count++
// Decide to switch to EMA stage
if ema.warmupCount >= ema.warmupWindow {
ema.currentStage = emaStage
}
} else {
// Immediately reset on any missing values during warm-up.
ema.resetStages()
}
// Emit valid output during emaStage or during warm-up if configured to do so.
if ema.currentStage == emaStage || ema.validDuringWarmup {
// Emit the avg value of input signal during the warm-up window.
avg, err := ema.computeAverage()
if err != nil {
return retErr(err)
}
output = avg
} else {
output = runtime.InvalidReading()
}
case emaStage:
if input.Valid() {
if !ema.lastGoodOutput.Valid() {
err := errors.New("ema: last good output is invalid")
logger.Error().Err(err).Msg("This is unexpected!")
return retErr(err)
}
// Compute the new outputValue.
outputValue := (ema.alpha * input.Value()) + ((1 - ema.alpha) * ema.lastGoodOutput.Value())
output = runtime.NewReading(outputValue)
} else {
ema.invalidCount++
// If invalid count is greater than the ema window, reset the stages.
if ema.invalidCount >= ema.emaWindow {
ema.resetStages()
}
// emit last good EMA value
output = ema.lastGoodOutput
}
default:
logger.Panic().Msg("unexpected ema stage")
}
// Set the last good output
if output.Valid() {
// apply correction
var err error
output, err = ema.applyCorrection(output, minEnvelope, maxEnvelope)
if err != nil {
return retErr(err)
}
ema.lastGoodOutput = output
}
// Returns Exponential Moving Average of a series of readings.
return runtime.PortToValue{
"output": []runtime.Reading{output},
}, nil
}
func (ema *EMA) computeAverage() (runtime.Reading, error) {
if ema.count > 0 {
avg := ema.sum / (ema.count)
return runtime.NewReading(avg), nil
} else {
return runtime.InvalidReading(), nil
}
}
// DynamicConfigUpdate is a no-op for EMA.
func (ema *EMA) DynamicConfigUpdate(event notifiers.Event, unmarshaller config.Unmarshaller) {}
func (ema *EMA) applyCorrection(output, minEnvelope, maxEnvelope runtime.Reading) (runtime.Reading, error) {
value := output.Value()
minxMaxConstraints := constraints.NewMinMaxConstraints()
if maxEnvelope.Valid() {
maxErr := minxMaxConstraints.SetMax(maxEnvelope.Value())
if maxErr != nil {
return runtime.InvalidReading(), maxErr
}
}
if minEnvelope.Valid() {
minErr := minxMaxConstraints.SetMin(minEnvelope.Value())
if minErr != nil {
return runtime.InvalidReading(), minErr
}
}
_, constraintType := minxMaxConstraints.Constrain(value)
correctedValue := value
if constraintType == constraints.MinConstraint && ema.correctionFactorOnMinViolation != 1 {
correctedValue = value * ema.correctionFactorOnMinViolation
} else if constraintType == constraints.MaxConstraint && ema.correctionFactorOnMaxViolation != 1 {
correctedValue = value * ema.correctionFactorOnMaxViolation
}
return runtime.NewReading(correctedValue), nil
}