2020-11-19 06:17:00 -06:00
|
|
|
package mathexp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/data"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Resample turns the Series into a Number based on the given reduction function
|
2021-04-23 09:52:32 -05:00
|
|
|
func (s Series) Resample(refID string, interval time.Duration, downsampler string, upsampler string, from, to time.Time) (Series, error) {
|
|
|
|
newSeriesLength := int(float64(to.Sub(from).Nanoseconds()) / float64(interval.Nanoseconds()))
|
2020-11-19 06:17:00 -06:00
|
|
|
if newSeriesLength <= 0 {
|
|
|
|
return s, fmt.Errorf("the series cannot be sampled further; the time range is shorter than the interval")
|
|
|
|
}
|
2021-06-02 11:29:19 -05:00
|
|
|
resampled := NewSeries(refID, s.GetLabels(), newSeriesLength+1)
|
2020-11-19 06:17:00 -06:00
|
|
|
bookmark := 0
|
|
|
|
var lastSeen *float64
|
|
|
|
idx := 0
|
2021-04-23 09:52:32 -05:00
|
|
|
t := from
|
|
|
|
for !t.After(to) && idx <= newSeriesLength {
|
2020-11-19 06:17:00 -06:00
|
|
|
vals := make([]*float64, 0)
|
|
|
|
sIdx := bookmark
|
|
|
|
for {
|
|
|
|
if sIdx == s.Len() {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
st, v := s.GetPoint(sIdx)
|
|
|
|
if st.After(t) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
bookmark++
|
|
|
|
sIdx++
|
|
|
|
lastSeen = v
|
|
|
|
vals = append(vals, v)
|
|
|
|
}
|
|
|
|
var value *float64
|
|
|
|
if len(vals) == 0 { // upsampling
|
|
|
|
switch upsampler {
|
|
|
|
case "pad":
|
|
|
|
if lastSeen != nil {
|
|
|
|
value = lastSeen
|
|
|
|
} else {
|
|
|
|
value = nil
|
|
|
|
}
|
|
|
|
case "backfilling":
|
|
|
|
if sIdx == s.Len() { // no vals left
|
|
|
|
value = nil
|
|
|
|
} else {
|
|
|
|
_, value = s.GetPoint(sIdx)
|
|
|
|
}
|
|
|
|
case "fillna":
|
|
|
|
value = nil
|
|
|
|
default:
|
|
|
|
return s, fmt.Errorf("upsampling %v not implemented", upsampler)
|
|
|
|
}
|
|
|
|
} else { // downsampling
|
|
|
|
fVec := data.NewField("", s.GetLabels(), vals)
|
2021-04-01 13:33:35 -05:00
|
|
|
ff := Float64Field(*fVec)
|
2020-11-19 06:17:00 -06:00
|
|
|
var tmp *float64
|
|
|
|
switch downsampler {
|
|
|
|
case "sum":
|
2021-04-01 13:33:35 -05:00
|
|
|
tmp = Sum(&ff)
|
2020-11-19 06:17:00 -06:00
|
|
|
case "mean":
|
2021-04-01 13:33:35 -05:00
|
|
|
tmp = Avg(&ff)
|
2020-11-19 06:17:00 -06:00
|
|
|
case "min":
|
2021-04-01 13:33:35 -05:00
|
|
|
tmp = Min(&ff)
|
2020-11-19 06:17:00 -06:00
|
|
|
case "max":
|
2021-04-01 13:33:35 -05:00
|
|
|
tmp = Max(&ff)
|
2020-11-19 06:17:00 -06:00
|
|
|
default:
|
|
|
|
return s, fmt.Errorf("downsampling %v not implemented", downsampler)
|
|
|
|
}
|
|
|
|
value = tmp
|
|
|
|
}
|
2021-06-02 11:29:19 -05:00
|
|
|
if err := resampled.SetPoint(idx, t, value); err != nil {
|
2020-11-19 06:17:00 -06:00
|
|
|
return resampled, err
|
|
|
|
}
|
|
|
|
t = t.Add(interval)
|
|
|
|
idx++
|
|
|
|
}
|
|
|
|
return resampled, nil
|
|
|
|
}
|