-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeavg.py
43 lines (38 loc) · 1.25 KB
/
timeavg.py
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
from collections import deque
import numpy as np
class TimeAvg():
def __init__(self, delta_t):
self.delta_t = delta_t
self.stream = deque()
def append(self, datapoint):
stream = self.stream
stream.append(datapoint) # appends on the right
length = len(stream)
if length < 1:
return -1
real_delta_t = stream[length - 1][1] - stream[0][1]
while real_delta_t > self.delta_t:
stream.popleft()
length -= 1
real_delta_t = stream[length - 1][1] - stream[0][1]
def calculate(self):
stream = self.stream
length = len(stream)
if length < 1:
return -1
real_delta_t = stream[length - 1][1] - stream[0][1]
while real_delta_t > self.delta_t:
stream.popleft()
length -= 1
real_delta_t = stream[length - 1][1] - stream[0][1]
y = np.array(stream)[:, 0]
t = np.array(stream)[:, 1]
return np.trapz(y, x=t) / (real_delta_t)
if __name__ == '__main__':
import time
import random
reading = TimeAvg(3)
t0 = time.time()
while time.time() < t0 + 15:
reading.append([random.randint(0, 10), time.time()])
print(reading.calculate())