This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
func_nonnegativederivative.go
82 lines (67 loc) · 1.86 KB
/
func_nonnegativederivative.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
package expr
import (
"fmt"
"math"
"github.com/grafana/metrictank/api/models"
"github.com/grafana/metrictank/consolidation"
"github.com/grafana/metrictank/schema"
)
type FuncNonNegativeDerivative struct {
in GraphiteFunc
maxValue float64
}
func NewNonNegativeDerivative() GraphiteFunc {
return &FuncNonNegativeDerivative{maxValue: math.NaN()}
}
func (s *FuncNonNegativeDerivative) Signature() ([]Arg, []Arg) {
return []Arg{
ArgSeriesList{val: &s.in},
ArgFloat{
key: "maxValue",
opt: true,
val: &s.maxValue}}, []Arg{ArgSeriesList{}}
}
func (s *FuncNonNegativeDerivative) Context(context Context) Context {
return context
}
func (s *FuncNonNegativeDerivative) Exec(dataMap DataMap) ([]models.Series, error) {
series, err := s.in.Exec(dataMap)
if err != nil {
return nil, err
}
outSeries := make([]models.Series, 0, len(series))
for _, serie := range series {
out := pointSlicePool.Get().([]schema.Point)
prev := math.NaN()
for _, p := range serie.Datapoints {
var delta float64
delta, prev = nonNegativeDelta(p.Val, prev, s.maxValue)
p.Val = delta
out = append(out, p)
}
serie.Target = fmt.Sprintf("nonNegativeDerivative(%s)", serie.Target)
serie.QueryPatt = fmt.Sprintf("nonNegativeDerivative(%s)", serie.QueryPatt)
serie.Tags = serie.CopyTagsWith("nonNegativeDerivative", "1")
serie.Datapoints = out
serie.Consolidator = consolidation.None
serie.QueryCons = consolidation.None
outSeries = append(outSeries, serie)
}
dataMap.Add(Req{}, outSeries...)
return outSeries, nil
}
func nonNegativeDelta(val, prev, maxValue float64) (float64, float64) {
if val > maxValue {
return math.NaN(), math.NaN()
}
if math.IsNaN(prev) || math.IsNaN(val) {
return math.NaN(), val
}
if val >= prev {
return val - prev, val
}
if !math.IsNaN(maxValue) {
return maxValue + 1 + val - prev, val
}
return math.NaN(), val
}