-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_series.py
More file actions
61 lines (52 loc) · 1.89 KB
/
time_series.py
File metadata and controls
61 lines (52 loc) · 1.89 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class TimeSeries(object):
"""Basic TimeSeries class
Takes a tuple of (x,y) values as data"""
def __init__(self, data):
self.data = data
def get(self, x):
for (xi,yi) in self.data:
if xi == x:
return yi
raise Exception("Didn't find the value")
def view(self):
'''A method for viewing the data in the TimeSeries object'''
pass
class StepFunctionTimeSeries(TimeSeries):
"""Interpolates between values as a step function"""
def get(self, x):
closest_point = None
for (xi, yi) in self.data:
if closest_point is None:
closest_point = (xi, yi)
else:
cx, cy = closest_point
if abs(xi-x) < abs(cx-x):
closest_point = (xi, yi)
return closest_point[1]
class LinearTimeSeries(TimeSeries):
"""Linear interpolation between values"""
def __init__(self, data):
TimeSeries.__init__(self, data)
self.data.sort()
def get(self, x):
# if it's out of range to the left,
# return the first value
if x < self.data[0][0]:
return self.data[0][1]
# if it's out of range to the right,
# return the last value
elif x > self.data[-1][0]:
return self.data[-1][1]
# otherwise, it's within the range
for (n, (xi, yi)) in enumerate(self.data):
if xi == x:
return yi
elif xi > x:
n1, n2 = n-1, n
x1, x2 = self.data[n1][0], self.data[n2][0]
y1, y2 = self.data[n1][1], self.data[n2][1]
d1, d2 = abs(x-x1), abs(x-x2)
total_weight = float(d1 + d2)
w1 = y1 * (total_weight-d1) / total_weight
w2 = y2 * (total_weight-d2) / total_weight
return w1 + w2