-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_diff_methods.py
More file actions
306 lines (294 loc) · 18.2 KB
/
test_diff_methods.py
File metadata and controls
306 lines (294 loc) · 18.2 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import numpy as np
from pytest import mark
from warnings import warn
from ..finite_difference import first_order, second_order, fourth_order
from ..linear_model import lineardiff, spectraldiff, rbfdiff
from ..polynomial_fit import polydiff, savgoldiff, splinediff
from ..total_variation_regularization import velocity, acceleration, jerk, iterative_velocity, smooth_acceleration, jerk_sliding
from ..kalman_smooth import rtsdiff, constant_velocity, constant_acceleration, constant_jerk
from ..smooth_finite_difference import mediandiff, meandiff, gaussiandiff, friedrichsdiff, butterdiff
# Function aliases for testing cases where parameters change the behavior in a big way, so error limits can be indexed in dict
def iterated_second_order(*args, **kwargs): return second_order(*args, **kwargs)
def iterated_fourth_order(*args, **kwargs): return fourth_order(*args, **kwargs)
def spline_irreg_step(*args, **kwargs): return splinediff(*args, **kwargs)
dt = 0.1
t = np.linspace(0, 3, 31) # sample locations, including the endpoint
tt = np.linspace(0, 3) # full domain, for visualizing denser plots
np.random.seed(7) # for repeatability of the test, so we don't get random failures
noise = 0.05*np.random.randn(*t.shape)
t_irreg = t + np.random.uniform(-dt/3, dt/3, *t.shape) # add jostle
# Analytic (function, derivative) pairs on which to test differentiation methods.
test_funcs_and_derivs = [
(0, r"$x(t)=1$", lambda t: np.ones(t.shape), lambda t: np.zeros(t.shape)), # constant
(1, r"$x(t)=2t+1$", lambda t: 2*t + 1, lambda t: 2*np.ones(t.shape)), # affine
(2, r"$x(t)=t^2-t+1$", lambda t: t**2 - t + 1, lambda t: 2*t - 1), # quadratic
(3, r"$x(t)=\sin(3t)+1/2$", lambda t: np.sin(3*t) + 1/2, lambda t: 3*np.cos(3*t)), # sinuoidal
(4, r"$x(t)=e^t\sin(5t)$", lambda t: np.exp(t)*np.sin(5*t), # growing sinusoidal
lambda t: np.exp(t)*(5*np.cos(5*t) + np.sin(5*t))),
(5, r"$x(t)=\frac{\sin(8t)}{(t+0.1)^{3/2}}$", lambda t: np.sin(8*t)/((t + 0.1)**(3/2)), # steep challenger
lambda t: ((0.8 + 8*t)*np.cos(8*t) - 1.5*np.sin(8*t))/(0.1 + t)**(5/2))]
# Call both ways, with kwargs (new) and with params list and optional options dict (legacy), to ensure both work
diff_methods_and_params = [
(first_order, {}), (second_order, {}), (fourth_order, {}), # empty dictionary for the case of no parameters
(iterated_second_order, {'num_iterations':5}), (iterated_fourth_order, {'num_iterations':10}),
(meandiff, {'window_size':3, 'num_iterations':2}), (meandiff, [3, 2], {'iterate':True}),
(mediandiff, {'window_size':3, 'num_iterations':2}), (mediandiff, [3, 2], {'iterate':True}),
(gaussiandiff, {'window_size':5}), (gaussiandiff, [5]),
(friedrichsdiff, {'window_size':5}), (friedrichsdiff, [5]),
(butterdiff, {'filter_order':3, 'cutoff_freq':0.074}), (butterdiff, [3, 0.074]),
(splinediff, {'degree':5, 's':2}), (splinediff, [5, 2]),
(spline_irreg_step, {'degree':5, 's':2}),
(polydiff, {'degree':2, 'window_size':3}), (polydiff, [2, 3]),
(savgoldiff, {'degree':2, 'window_size':5, 'smoothing_win':5}), (savgoldiff, [2, 5, 5]),
(constant_velocity, {'r':1e-2, 'q':1e3}), (constant_velocity, [1e-2, 1e3]),
(constant_acceleration, {'r':1e-3, 'q':1e4}), (constant_acceleration, [1e-3, 1e4]),
(constant_jerk, {'r':1e-4, 'q':1e5}), (constant_jerk, [1e-4, 1e5]),
(rtsdiff, {'order':2, 'qr_ratio':1e7, 'forwardbackward':True}),
(velocity, {'gamma':0.5}), (velocity, [0.5]),
(acceleration, {'gamma':1}), (acceleration, [1]),
(jerk, {'gamma':10}), (jerk, [10]),
(iterative_velocity, {'num_iterations':5, 'gamma':0.05}), (iterative_velocity, [5, 0.05]),
(smooth_acceleration, {'gamma':2, 'window_size':5}), (smooth_acceleration, [2, 5]),
(jerk_sliding, {'gamma':1, 'window_size':15}), (jerk_sliding, [1], {'window_size':15}),
(spectraldiff, {'high_freq_cutoff':0.2}), (spectraldiff, [0.2]),
(lineardiff, {'order':3, 'gamma':5, 'window_size':11, 'solver':'CLARABEL'}), (lineardiff, [3, 5, 11], {'solver':'CLARABEL'}),
(rbfdiff, {'sigma':0.5, 'lmbd':0.001})
]
# All the testing methodology follows the exact same pattern; the only thing that changes is the
# closeness to the right answer various methods achieve with the given parameterizations and random seed.
# So index a big ol' table by method, then by test function number, and finally by the truth-result pair
# being compared. The tuples are order of magnitude of (L2,Linf) distances for pairs
# (x,x_hat), (dxdt,dxdt_hat), (x,x_hat_noisy), (dxdt,dxdt_hat_noisy).
error_bounds = {
first_order: [[(-25, -25), (-25, -25), (0, 0), (1, 1)],
[(-25, -25), (-13, -13), (0, 0), (1, 1)],
[(-25, -25), (0, 0), (0, 0), (1, 1)],
[(-25, -25), (1, 0), (0, 0), (1, 1)],
[(-25, -25), (2, 2), (0, 0), (2, 2)],
[(-25, -25), (3, 3), (0, 0), (3, 3)]],
second_order: [[(-25, -25), (-25, -25), (0, 0), (1, 1)],
[(-25, -25), (-13, -13), (0, 0), (1, 1)],
[(-25, -25), (-13, -13), (0, 0), (1, 1)],
[(-25, -25), (0, -1), (0, 0), (1, 1)],
[(-25, -25), (1, 1), (0, 0), (1, 1)],
[(-25, -25), (3, 3), (0, 0), (3, 3)]],
iterated_second_order: [[(-9, -10), (-25, -25), (0, -1), (0, 0)],
[(-9, -10), (-14, -14), (0, -1), (0, 0)],
[(-1, -1), (0, 0), (0, -1), (0, 0)],
[(0, 0), (1, 0), (0, 0), (1, 0)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
fourth_order: [[(-25, -25), (-25, -25), (0, 0), (1, 1)],
[(-25, -25), (-13, -13), (0, 0), (1, 1)],
[(-25, -25), (-13, -13), (0, 0), (1, 1)],
[(-25, -25), (-2, -2), (0, 0), (1, 1)],
[(-25, -25), (1, 0), (0, 0), (1, 1)],
[(-25, -25), (2, 2), (0, 0), (2, 2)]],
iterated_fourth_order: [[(-9, -10), (-25, -25), (0, -1), (0, 0)],
[(-9, -10), (-13, -13), (0, -1), (0, 0)],
[(-1, -1), (0, 0), (-1, -1), (0, 0)],
[(0, -1), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
meandiff: [[(-25, -25), (-25, -25), (0, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
mediandiff: [[(-25, -25), (-25, -25), (-1, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(-1, -1), (0, 0), (0, 0), (1, 1)],
[(0, 0), (2, 2), (0, 0), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
gaussiandiff: [[(-14, -15), (-14, -14), (0, -1), (1, 0)],
[(-1, -1), (1, 0), (0, 0), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(0, -1), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
friedrichsdiff: [[(-25, -25), (-25, -25), (0, -1), (1, 0)],
[(-1, -1), (1, 0), (0, 0), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(0, -1), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
butterdiff: [[(-13, -14), (-13, -13), (0, -1), (0, 0)],
[(0, -1), (0, 0), (0, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 0), (1, 1), (1, 0), (1, 1)],
[(2, 2), (3, 2), (2, 2), (3, 2)],
[(2, 1), (3, 3), (2, 1), (3, 3)]],
splinediff: [[(-14, -15), (-14, -15), (-1, -1), (0, 0)],
[(-14, -14), (-13, -14), (-1, -1), (0, 0)],
[(-14, -14), (-13, -13), (-1, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 0), (2, 2), (1, 0), (2, 2)],
[(1, 0), (3, 3), (1, 0), (3, 3)]],
spline_irreg_step: [[(-14, -14), (-14, -14), (-1, -1), (0, 0)],
[(-14, -14), (-13, -13), (-1, -1), (0, 0)],
[(-14, -14), (-13, -13), (-1, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 0), (2, 2), (1, 0), (2, 2)],
[(1, 0), (3, 3), (1, 0), (3, 3)]],
polydiff: [[(-14, -15), (-14, -14), (0, -1), (1, 1)],
[(-14, -14), (-13, -13), (0, -1), (1, 1)],
[(-14, -14), (-13, -13), (0, -1), (1, 1)],
[(-2, -2), (0, 0), (0, -1), (1, 1)],
[(0, 0), (1, 1), (0, -1), (1, 1)],
[(0, 0), (3, 3), (0, 0), (3, 3)]],
savgoldiff: [[(-9, -10), (-13, -14), (0, -1), (0, 0)],
[(-9, -10), (-13, -13), (0, -1), (0, 0)],
[(-2, -2), (-1, -1), (0, -1), (0, 0)],
[(0, -1), (0, 0), (0, 0), (1, 0)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
velocity: [[(-25, -25), (-18, -19), (0, -1), (1, 0)],
[(-12, -12), (-11, -12), (-1, -1), (-1, -2)],
[(0, 0), (1, 0), (0, 0), (1, 0)],
[(0, -1), (1, 1), (0, 0), (1, 0)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 0), (3, 3), (1, 0), (3, 3)]],
acceleration: [[(-25, -25), (-18, -18), (0, -1), (0, 0)],
[(-10, -10), (-9, -9), (-1, -1), (0, -1)],
[(-10, -10), (-9, -10), (-1, -1), (0, -1)],
[(0, -1), (1, 0), (0, -1), (1, 0)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
jerk: [[(-25, -25), (-18, -18), (-1, -1), (0, 0)],
[(-9, -10), (-9, -9), (-1, -1), (0, 0)],
[(-10, -10), (-9, -10), (-1, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
iterative_velocity: [[(-9, -10), (-25, -25), (0, -1), (0, 0)],
[(0, 0), (0, 0), (0, 0), (1, 0)],
[(0, 0), (1, 0), (1, 0), (1, 0)],
[(1, 0), (1, 1), (1, 0), (1, 1)],
[(2, 1), (2, 2), (2, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
smooth_acceleration: [[(-9, -10), (-18, -18), (0, -1), (0, 0)],
[(-9, -9), (-10, -10), (-1, -1), (-1, -1)],
[(-2, -2), (-1, -1), (-1, -1), (0, -1)],
[(0, 0), (1, 0), (0, -1), (1, 0)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
jerk_sliding: [[(-15, -15), (-16, -16), (0, -1), (1, 0)],
[(-14, -14), (-14, -14), (0, -1), (0, 0)],
[(-14, -14), (-14, -14), (0, -1), (0, 0)],
[(-1, -1), (0, 0), (0, -1), (1, 0)],
[(0, 0), (2, 2), (0, 0), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
constant_velocity: [[(-25, -25), (-25, -25), (0, -1), (1, 1)],
[(-4, -5), (-3, -3), (0, -1), (1, 1)],
[(-3, -3), (0, 0), (0, -1), (1, 1)],
[(-3, -3), (1, 0), (0, -1), (1, 1)],
[(-1, -1), (2, 2), (0, 0), (2, 2)],
[(-1, -1), (3, 3), (0, 0), (3, 3)]],
constant_acceleration: [[(-25, -25), (-25, -25), (0, -1), (1, 1)],
[(-5, -5), (-4, -4), (0, -1), (1, 1)],
[(-4, -5), (-3, -3), (0, -1), (1, 1)],
[(-3, -3), (0, 0), (0, -1), (1, 1)],
[(-1, -1), (1, 1), (0, -1), (1, 1)],
[(0, 0), (3, 3), (0, 0), (3, 3)]],
constant_jerk: [[(-25, -25), (-25, -25), (0, -1), (1, 1)],
[(-6, -6), (-5, -5), (0, -1), (1, 1)],
[(-5, -5), (-4, -4), (0, -1), (1, 1)],
[(-3, -3), (-1, -1), (0, -1), (1, 1)],
[(-1, -1), (1, 1), (0, -1), (1, 1)],
[(0, 0), (3, 3), (0, 0), (3, 3)]],
rtsdiff: [[(-25, -25), (-25, -25), (0, -1), (1, 1)],
[(-5, -5), (-4, -4), (0, -1), (1, 1)],
[(-4, -4), (-3, -3), (0, -1), (1, 1)],
[(-2, -3), (0, 0), (0, -1), (1, 1)],
[(-1, -2), (1, 1), (0, -1), (1, 1)],
[(0, 0), (3, 3), (0, 0), (3, 3)]],
spectraldiff: [[(-9, -10), (-14, -15), (-1, -1), (0, 0)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 1), (1, 1), (1, 1), (1, 1)],
[(0, 0), (1, 1), (0, 0), (1, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
lineardiff: [[(-6, -6), (-5, -6), (0, -1), (0, 0)],
[(0, 0), (2, 1), (0, 0), (2, 1)],
[(1, 0), (2, 2), (1, 0), (2, 2)],
[(1, 0), (2, 1), (1, 0), (2, 1)],
[(1, 1), (2, 2), (1, 1), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]],
rbfdiff: [[(-2, -2), (0, 0), (0, -1), (0, 0)],
[(-1, -1), (1, 0), (0, -1), (1, 1)],
[(-1, -1), (1, 1), (0, -1), (1, 1)],
[(-2, -2), (0, 0), (0, -1), (0, 0)],
[(0, 0), (2, 2), (0, 0), (2, 2)],
[(1, 1), (3, 3), (1, 1), (3, 3)]]
}
# Essentially run the cartesian product of [diff methods] x [test functions] through this one test
@mark.filterwarnings("ignore::DeprecationWarning") # I want to test the old and new functionality intentionally
@mark.parametrize("diff_method_and_params", diff_methods_and_params) # things like splinediff, with their parameters
@mark.parametrize("test_func_and_deriv", test_funcs_and_derivs) # analytic functions, with their true derivatives
def test_diff_method(diff_method_and_params, test_func_and_deriv, request): # request gives access to context
# unpack
diff_method, params = diff_method_and_params[:2]
if len(diff_method_and_params) == 3: options = diff_method_and_params[2] # optionally pass old-style `options` dict
i, latex_name, f, df = test_func_and_deriv
# some methods rely on cvxpy, and we'd like to allow use of pynumdiff without convex optimization
if diff_method in [lineardiff, velocity, acceleration, jerk, smooth_acceleration]:
try: import cvxpy
except: warn(f"Cannot import cvxpy, skipping {diff_method} test."); return
# sample the true function and true derivative, and make noisy samples
if diff_method in [spline_irreg_step, rtsdiff, rbfdiff]: # list that can handle variable dt
x = f(t_irreg)
dxdt = df(t_irreg)
_t = t_irreg
else:
x = f(t)
dxdt = df(t)
_t = dt
x_noisy = x + noise
# differentiate without and with noise, accounting for new and old styles of calling functions
x_hat, dxdt_hat = diff_method(x, _t, **params) if isinstance(params, dict) \
else diff_method(x, _t, params) if (isinstance(params, list) and len(diff_method_and_params) < 3) \
else diff_method(x, _t, params, options)
x_hat_noisy, dxdt_hat_noisy = diff_method(x_noisy, _t, **params) if isinstance(params, dict) \
else diff_method(x_noisy, _t, params) if (isinstance(params, list) and len(diff_method_and_params) < 3) \
else diff_method(x_noisy, _t, params, options)
# plotting code
if request.config.getoption("--plot") and not isinstance(params, list): # Get the plot flag from pytest configuration
fig, axes = request.config.plots[diff_method] # get the appropriate plot, set up by the store_plots fixture in conftest.py
t_ = t_irreg if diff_method in [spline_irreg_step, rtsdiff, rbfdiff] else t
axes[i, 0].plot(t_, f(t_))
axes[i, 0].plot(t_, x, 'C0+')
axes[i, 0].plot(t_, x_hat, 'C2.', ms=4)
axes[i, 0].plot(tt, df(tt))
axes[i, 0].plot(t_, dxdt_hat, 'C1+')
axes[i, 0].set_ylabel(latex_name, rotation=0, labelpad=50)
if i < len(test_funcs_and_derivs)-1: axes[i, 0].set_xticklabels([])
else: axes[i, 0].set_xlabel('t')
if i == 0: axes[i, 0].set_title('noiseless')
axes[i, 1].plot(t_, f(t_), label=r"$x(t)$")
axes[i, 1].plot(t_, x_noisy, 'C0+', label=r"$x_n$")
axes[i, 1].plot(t_, x_hat_noisy, 'C2.', ms=4, label=r"$\hat{x}_n$")
axes[i, 1].plot(tt, df(tt), label=r"$\frac{dx(t)}{dt}$")
axes[i, 1].plot(t_, dxdt_hat_noisy, 'C1+', label=r"$\hat{\frac{dx}{dt}}_n$")
if i < len(test_funcs_and_derivs)-1: axes[i, 1].set_xticklabels([])
else: axes[i, 1].set_xlabel('t')
axes[i, 1].set_yticklabels([])
if i == 0: axes[i, 1].set_title('with noise')
# check x_hat and x_hat_noisy are close to x and that dxdt_hat and dxdt_hat_noisy are close to dxdt
if request.config.getoption("--bounds"): print("\n[", end="") # print stuff if the user gave the --bounds flag
for j,(a,b) in enumerate([(x,x_hat), (dxdt,dxdt_hat), (x,x_hat_noisy), (dxdt,dxdt_hat_noisy)]):
l2_error = np.linalg.norm(a - b)
linf_error = np.max(np.abs(a - b))
# bounds-printing for establishing bounds
if request.config.getoption("--bounds"):
#print(f"({l2_error},{linf_error})", end=", ") # <- in case you want to print actual errors rather than powers
print(f"({int(np.ceil(np.log10(l2_error))) if l2_error > 0 else -25}, {int(np.ceil(np.log10(linf_error))) if linf_error > 0 else -25})", end=", ")
# bounds checking
else:
log_l2_bound, log_linf_bound = error_bounds[diff_method][i][j]
assert l2_error < 10**log_l2_bound
assert linf_error < 10**log_linf_bound
# methods that get super duper close can converge to different very small limits on different runs
if 1e-18 < l2_error < 10**(log_l2_bound - 1) or 1e-18 < linf_error < 10**(log_linf_bound - 1):
print(f"Improvement detected for method {diff_method.__name__}")