Skip to content

Commit 84e3cb5

Browse files
Add tests for the TimeseriesAvg
1 parent 244cc13 commit 84e3cb5

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# License: MIT
2+
# Copyright © 2023 Frequenz Energy-as-a-Service GmbH
3+
4+
"""Tests for the timeseries averager."""
5+
6+
import asyncio
7+
from datetime import datetime, timedelta
8+
from typing import List
9+
# import numpy as np
10+
import logging
11+
# from frequenz.channels import Broadcast, Sender
12+
#
13+
# from frequenz.sdk.timeseries import Sample
14+
from frequenz.sdk.timeseries.timeseries_avg import TimeseriesAvg
15+
16+
from test_moving_window import init_moving_window, push_lm_data
17+
18+
# TODO Tests
19+
# * moving intervals into ts timeseries_avg
20+
# * test the average calculation for all cases
21+
# * test with all zero init_moving_window
22+
# * run tests with different sample periods
23+
24+
async def create_ts_avg(data: List[float], weights: List[float] | None = None) -> TimeseriesAvg:
25+
window, sender = init_moving_window(len(data))
26+
await push_lm_data(sender, data)
27+
28+
return TimeseriesAvg(
29+
moving_window = window, # 28 days moving window
30+
distance=timedelta(seconds=5),
31+
weights = weights,
32+
)
33+
34+
def test_interval_shifting(ts_avg: TimeseriesAvg):
35+
"""
36+
Test if a interval is properly shifted into a moving window
37+
38+
We consider the following case:
39+
40+
moving_window = [1,2,2,1,1,1,2,2,1]
41+
the window starts at Jan. 01 2023 at 00:00:00
42+
"""
43+
# Test if the timestamp is not shifted
44+
ts = datetime(2023, 1, 1, 0, 0, 1)
45+
index_not_shifted = ts_avg._shift_ts_to_window(ts)
46+
assert(index_not_shifted == 1)
47+
48+
# Test if a timestamp in the window is shifted to the first appearance of the window
49+
ts = datetime(2023, 1, 1, 0, 0, 6)
50+
index_shifted = ts_avg._shift_ts_to_window(ts)
51+
assert(index_shifted == 1)
52+
53+
# Test if a timestamp outside the window is shifted
54+
ts = datetime(2023, 1, 1, 0, 0, 11)
55+
index_shifted = ts_avg._shift_ts_to_window(ts)
56+
assert(index_shifted == 1)
57+
58+
59+
async def test_ts_avg(ts_avg: TimeseriesAvg):
60+
window, sender = init_moving_window(10)
61+
await push_lm_data(sender,[1, 2, 3, 4, 5, 6, 7, 8, 9, 1])
62+
63+
ts_avg = TimeseriesAvg(
64+
moving_window = window, # 28 days moving window
65+
distance=timedelta(days=7),
66+
weights=[0.1, 0.2, 0.3, 0.5]
67+
)
68+
69+
async def tests():
70+
""" Temporary function until this is started by pytest."""
71+
ts_avg = await create_ts_avg([1,2,2,1,1,1,2,2,1])
72+
test_interval_shifting(ts_avg)
73+
# await test_ts_avg()
74+
75+
logging.basicConfig(level=logging.DEBUG)
76+
asyncio.run(tests())

0 commit comments

Comments
 (0)