Skip to content
This repository has been archived by the owner on Oct 17, 2018. It is now read-only.

Commit

Permalink
perSecond returns empty datapoint for negative rate
Browse files Browse the repository at this point in the history
  • Loading branch information
xichen2020 committed Jul 6, 2018
1 parent 52e808d commit d6fdb6e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
11 changes: 10 additions & 1 deletion transformation/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,19 @@ const (
nanosPerSecond = time.Second / time.Nanosecond
)

// perSecond computes the derivative between consecutive datapoints, taking into
// account the time interval between the values.
// * It skips NaN values.
// * It assumes the timestamps are monotonically increasing, and values are non-decreasing.
// If either of the two conditions is not met, an empty datapoint is returned.
func perSecond(prev, curr Datapoint) Datapoint {
if prev.TimeNanos >= curr.TimeNanos || math.IsNaN(prev.Value) || math.IsNaN(curr.Value) {
return emptyDatapoint
}
rate := (curr.Value - prev.Value) * float64(nanosPerSecond) / float64(curr.TimeNanos-prev.TimeNanos)
diff := curr.Value - prev.Value
if diff < 0 {
return emptyDatapoint
}
rate := diff * float64(nanosPerSecond) / float64(curr.TimeNanos-prev.TimeNanos)
return Datapoint{TimeNanos: curr.TimeNanos, Value: rate}
}
10 changes: 8 additions & 2 deletions transformation/binary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ func TestPerSecond(t *testing.T) {
},
{
prev: Datapoint{TimeNanos: time.Unix(1230, 0).UnixNano(), Value: 25},
curr: Datapoint{TimeNanos: time.Unix(1240, 0).UnixNano(), Value: 20},
expected: Datapoint{TimeNanos: time.Unix(1240, 0).UnixNano(), Value: -0.5},
curr: Datapoint{TimeNanos: time.Unix(1240, 0).UnixNano(), Value: 30},
expected: Datapoint{TimeNanos: time.Unix(1240, 0).UnixNano(), Value: 0.5},
},
{
prev: Datapoint{TimeNanos: time.Unix(1230, 0).UnixNano(), Value: 25},
Expand All @@ -63,6 +63,12 @@ func TestPerSecond(t *testing.T) {
expectedNaN: true,
expected: emptyDatapoint,
},
{
prev: Datapoint{TimeNanos: time.Unix(1230, 0).UnixNano(), Value: 30},
curr: Datapoint{TimeNanos: time.Unix(1240, 0).UnixNano(), Value: 20},
expectedNaN: true,
expected: emptyDatapoint,
},
}

for _, input := range inputs {
Expand Down

0 comments on commit d6fdb6e

Please sign in to comment.