Skip to content

Commit

Permalink
Forecast: fix accumulated energy calculation (#19547)
Browse files Browse the repository at this point in the history
  • Loading branch information
andig authored Mar 7, 2025
1 parent 7634645 commit ac09632
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
18 changes: 11 additions & 7 deletions core/site_tariffs.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,21 @@ func accumulatedEnergy(rr timeseries, from, to time.Time) float64 {
continue
}

start := last.Timestamp
if start.Before(from) {
start = from
x1 := last.Timestamp
y1 := last.Value
if x1.Before(from) {
x1 = from
y1 += float64(from.Sub(last.Timestamp)) * (r.Value - last.Value) / float64(r.Timestamp.Sub(last.Timestamp))
}

end := r.Timestamp
if end.After(to) {
end = to
x2 := r.Timestamp
y2 := r.Value
if x2.After(to) {
x2 = to
y2 += float64(to.Sub(r.Timestamp)) * (r.Value - last.Value) / float64(r.Timestamp.Sub(last.Timestamp))
}

energy += (r.Value + last.Value) / 2 * end.Sub(start).Hours()
energy += (y1 + y2) / 2 * x2.Sub(x1).Hours()

if !r.Timestamp.Before(to) {
break
Expand Down
10 changes: 7 additions & 3 deletions core/site_tariffs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,21 @@ func TestAccumulatedEnergy(t *testing.T) {
expected float64
}{
{0, 0, 0},
{0, 0.5, 0.25},
{0, 0.5, 0.125},
{0, 1, 0.5},
{1, 2, 1.5},
{0, 1.5, 1.125},
{0, 2, 2},
{1, 2, 1.5},
{0.25, 0.75, 0.25},
{0.5, 1, 0.375},
{0.5, 3.5, 6},
} {
t.Logf("%d. %+v", i+1, tc)

from := clock.Now().Add(time.Duration(float64(time.Hour) * tc.from))
to := clock.Now().Add(time.Duration(float64(time.Hour) * tc.to))

res := accumulatedEnergy(rr, from, to)
assert.Equal(t, tc.expected, res, "test case %d", i)
assert.Equal(t, tc.expected, res, "test case %d", i+1)
}
}

0 comments on commit ac09632

Please sign in to comment.