-
Notifications
You must be signed in to change notification settings - Fork 26
/
filters.py
282 lines (215 loc) · 7.17 KB
/
filters.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""
Given a list of numbers, convolve it by an arbitrary
weighting vector defined by a list of weights and an
offset
"""
import pandas as pd
from numba import jit
import numpy as np
from typing import List, Dict, Set
from utils.profiler import time_this, timed_report
from utils.profiler import ExponentialRange
def random_numeric_list(n: int) -> List[float]:
return list(np.random.random(n))
@time_this(lambda *args, **kwargs: len(args[0]))
def naive_filter(values: List[float], weights: List[float],
a: int) -> List[float]:
"""
This is O(nm) for a list of length n and weights of
length m because it makes no assumptions about the
shape of the weighting vector
"""
n, m = len(values), len(weights)
b = a + m - 1
# Exit early if m greater than length of values
if m > n or -a > n or b > n:
return [None] * len(values)
# Front and back padding of series
front_pad = max(-a, 0)
back_pad = max(b, 0)
# Apply front pad
y = [None] * front_pad
# Compute the filter
for i in range(front_pad, n - back_pad):
accumulator = 0
for j in range(m):
accumulator += weights[j] * values[i+j+a]
y.append(accumulator)
# Apply back pad
y.extend([None] * back_pad)
return y
@time_this(lambda *args, **kwargs: len(args[0]))
def smart_filter(values: List[float], weights: List[float],
a: int) -> List[float]:
"""
This is O(nm) for a list of length n and weights of
length m. Takes advantage of duplicate weights to save
calculations.
"""
n, m = len(values), len(weights)
b = a + m - 1
# Exit early if m greater than length of values
if m > n or -a > n or b > n:
return [None] * len(values)
# Front and back padding of series
front_pad = max(-a, 0)
back_pad = max(b, 0)
# Pre-compute scaled values for each unique weight
unique_weights: Set[float] = set(weights)
scaled_vectors: Dict[float, List[float]] = dict()
for w in unique_weights:
scaled_vectors[w] = [w * v for v in values]
# Apply front pad
y = [None] * front_pad
# Compute the moving average
for i in range(front_pad, n - back_pad):
accumulator = 0
for j, w in enumerate(weights):
accumulator += scaled_vectors[w][i+j+a]
y.append(accumulator)
# Apply back pad
y.extend([None] * back_pad)
return y
@time_this(lambda *args, **kwargs: len(args[0]))
def numpy_naive_filter(values: np.ndarray,
weights: np.ndarray, a: int) -> np.ndarray:
"""
This is O(nm) for a list of length n and weights of
length m because it makes no assumptions about the
shape of the weighting vector
"""
n, m = values.shape[0], weights.shape[0]
b = a + m - 1
# Exit early if m greater than length of values
if m > n or -a > n or b > n:
return np.array([np.nan]*n)
# Front and back padding of series
front_pad = max(-a, 0)
back_pad = max(b, 0)
# Initialize the output array
y = np.empty((n,))
# Pad with na values
y[:front_pad] = np.nan
y[-back_pad:] = np.nan
# Compute the filter
for i in range(front_pad, n - back_pad):
y[i] = weights.dot(values[(i+a):(i+a+m)])
return y
@time_this(lambda *args, **kwargs: len(args[0]))
def numpy_smart_filter(values: np.ndarray,
weights: np.ndarray, a: int) -> np.ndarray:
"""
This is O(nm) for a list of length n and weights of
length m. Takes advantage of duplicate weights to save
calculations.
"""
n, m = values.shape[0], weights.shape[0]
b = a + m - 1
# Exit early if m greater than length of values
if m > n or -a > n or b > n:
return np.array([np.nan]*n)
# Front and back padding of series
front_pad = max(-a, 0)
back_pad = max(b, 0)
# Initialize the output array
y = np.zeros((n,))
# Pad with na values
y[:front_pad] = np.nan
y[-back_pad:] = np.nan
unique_weights: Set[float] = set(weights)
scaled_vectors: Dict[float, np.ndarray] = dict()
for w in unique_weights:
scaled_vectors[w] = w * values
r1, r2 = front_pad, n-back_pad
for j, w in enumerate(weights):
v = scaled_vectors[w]
y[r1:r2] += v[(r1+j+a):(r2+a+j)]
return y
@time_this(lambda *args, **kwargs: len(args[0]))
def numpy_naive_matrix_filter(values: np.ndarray,
weights: np.ndarray, a: int) -> np.ndarray:
"""
This is O(nm) for a list of length n and weights of
length m. Takes advantage of duplicate weights to save
calculations.
"""
n, m = values.shape[0], weights.shape[0]
b = a + m - 1
# Exit early if m greater than length of values
if m > n or -a > n or b > n:
return np.array([np.nan]*n)
# Front and back padding of series
front_pad = max(-a, 0)
back_pad = max(b, 0)
# Initialize the output array
y = np.zeros((n,))
# Pad with na values
y[:front_pad] = np.nan
y[-back_pad:] = np.nan
# Build a matrix to multiply with weight vector
q = np.empty((n - front_pad - back_pad, m))
for j in range(m):
q[:,j] = values[j:(j+n-m+1)]
y[front_pad:-back_pad] = q.dot(weights)
return y
if __name__ == '__main__':
exp_range = ExponentialRange(2, 7, 1/4)
values = random_numeric_list(exp_range.max)
series_values = pd.Series(values)
np_values = np.array(values)
# _values = [1,2,3,4,5,6,7,8,9,10]
# _weights = [1,2,3,2,1]
# _a = -2
# print(naive_filter(_values, _weights, _a))
# print(smart_filter(_values, _weights, _a))
# print(
# numpy_naive_filter(
# np.array(_values),
# np.array(_weights),
# _a,
# )
# )
# print(
# numpy_smart_filter(
# np.array(_values),
# np.array(_weights),
# _a,
# )
# )
# print(
# numpy_naive_matrix_filter(
# np.array(_values),
# np.array(_weights),
# _a,
# )
# )
m = 21
weights = [1/m]*m
np_weights = np.array(weights)
a = -int((m-1)/2)
with timed_report():
for i in exp_range.iterator(6):
naive_filter(values[:i], weights, a)
for i in exp_range.iterator(6):
smart_filter(values[:i], weights, a)
for i in exp_range.iterator():
numpy_naive_filter(np_values[:i], np_weights, a)
for i in exp_range.iterator():
numpy_smart_filter(np_values[:i], np_weights, a)
for i in exp_range.iterator():
numpy_naive_matrix_filter(np_values[:i], np_weights, a)
m = 21
weights = list(np.random.random(m))
np_weights = np.array(weights)
a = -int((m-1)/2)
with timed_report():
for i in exp_range.iterator(6):
naive_filter(values[:i], weights, a)
for i in exp_range.iterator(6):
smart_filter(values[:i], weights, a)
for i in exp_range.iterator():
numpy_naive_filter(np_values[:i], np_weights, a)
for i in exp_range.iterator():
numpy_smart_filter(np_values[:i], np_weights, a)
for i in exp_range.iterator():
numpy_naive_matrix_filter(np_values[:i], np_weights, a)