forked from dynamicslab/pysindy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_differentiation.py
420 lines (353 loc) · 14.1 KB
/
test_differentiation.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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
"""
Unit tests for differentiation methods.
"""
import numpy as np
import pytest
from derivative import dxdt
from pysindy.differentiation import FiniteDifference
from pysindy.differentiation import SINDyDerivative
from pysindy.differentiation import SmoothedFiniteDifference
from pysindy.differentiation import SpectralDerivative
from pysindy.differentiation.base import BaseDifferentiation
@pytest.mark.parametrize(
"method",
[
FiniteDifference(),
SINDyDerivative(kind="spline", s=1),
SmoothedFiniteDifference(),
SpectralDerivative(),
],
)
def test_methods_store_smoothed_x_(data_derivative_1d, method):
x, _ = data_derivative_1d
assert not hasattr(method, "smoothed_x_")
method(x)
assert hasattr(method, "smoothed_x_")
assert x.shape == method.smoothed_x_.shape
def test_methods_smoothedfd_smooths(data_derivative_1d):
x, _ = data_derivative_1d
x_noisy = x + np.random.normal(size=x.shape)
method = SmoothedFiniteDifference()
_ = method(x_noisy)
result = method.smoothed_x_
assert np.linalg.norm(result - x) < np.linalg.norm(x_noisy - x)
def test_methods_smoothedfd_not_save_smooth(data_derivative_1d):
x, _ = data_derivative_1d
method = SmoothedFiniteDifference(save_smooth=False)
_ = method(x)
result = method.smoothed_x_
np.testing.assert_allclose(x, result)
def test_forward_difference_length():
x = 2 * np.linspace(1, 100, 100)
forward_difference = FiniteDifference(order=1)
assert len(forward_difference(x)) == len(x)
forward_difference_nans = FiniteDifference(order=1, drop_endpoints=True)
assert len(forward_difference_nans(x)) == len(x)
def test_forward_difference_variable_timestep_length():
t = np.linspace(1, 10, 100) ** 2
x = 2 * t
forward_difference = FiniteDifference(order=1)
assert len(forward_difference(x, t) == len(x))
def test_centered_difference_length():
x = 2 * np.linspace(1, 100, 100)
centered_difference = FiniteDifference(order=2)
assert len(centered_difference(x)) == len(x)
centered_difference_nans = FiniteDifference(order=2, drop_endpoints=True)
assert len(centered_difference_nans(x)) == len(x)
def test_centered_difference_variable_timestep_length():
t = np.linspace(1, 10, 100) ** 2
x = 2 * t
centered_difference = FiniteDifference(order=2)
assert len(centered_difference(x, t) == len(x))
def test_nan_derivatives(data_lorenz):
x, t = data_lorenz
x_dot = FiniteDifference(drop_endpoints=False)(x, t)
x_dot_nans = FiniteDifference(drop_endpoints=True)(x, t)
np.testing.assert_allclose(x_dot_nans[1:-1], x_dot[1:-1])
assert np.isnan(x_dot_nans[:1]).all() and np.isnan(x_dot_nans[-1:]).all()
def test_forward_difference_1d(data_derivative_1d):
x, x_dot = data_derivative_1d
forward_difference = FiniteDifference(order=1)
np.testing.assert_allclose(forward_difference(x), x_dot)
def test_forward_difference_2d(data_derivative_2d):
x, x_dot = data_derivative_2d
forward_difference = FiniteDifference(order=1)
np.testing.assert_allclose(forward_difference(x), x_dot)
def test_centered_difference_1d(data_derivative_1d):
x, x_dot = data_derivative_1d
centered_difference = FiniteDifference(order=2)
np.testing.assert_allclose(centered_difference(x), x_dot)
def test_spectral_derivative_1d(data_derivative_quasiperiodic_1d):
t, x, x_dot = data_derivative_quasiperiodic_1d
spectral_derivative = SpectralDerivative()
np.testing.assert_allclose(spectral_derivative(x, t), x_dot, atol=1e-12)
centered_difference = FiniteDifference(order=2, periodic=True)._differentiate(x, t)
np.testing.assert_allclose(
centered_difference[0], centered_difference[-1], rtol=1e-4
)
def test_centered_difference_2d(data_derivative_2d):
x, x_dot = data_derivative_2d
centered_difference = FiniteDifference(order=2)
np.testing.assert_allclose(centered_difference(x), x_dot)
def test_spectral_derivative_2d(data_derivative_quasiperiodic_2d):
t, x, x_dot = data_derivative_quasiperiodic_2d
spectral_derivative = SpectralDerivative()
np.testing.assert_allclose(spectral_derivative(x, t), x_dot, atol=1e-12)
centered_difference = FiniteDifference(order=2, periodic=True)._differentiate(x, t)
np.testing.assert_allclose(
centered_difference[0, 0], centered_difference[-1, 0], rtol=1e-4
)
def test_centered_difference_2d_uniform(data_derivative_2d):
x, x_dot = data_derivative_2d
centered_difference = FiniteDifference(order=2, is_uniform=True)
np.testing.assert_allclose(centered_difference(x), x_dot)
def test_centered_difference_2d_uniform_time(data_derivative_2d):
x, x_dot = data_derivative_2d
t = np.linspace(0, x.shape[0] - 1, x.shape[0])
centered_difference = FiniteDifference(order=2)
np.testing.assert_allclose(centered_difference(x, t), x_dot)
def test_centered_difference_2d_nonuniform_time(data_derivative_2d):
x, x_dot = data_derivative_2d
t = np.linspace(0, x.shape[0] - 1, x.shape[0])
centered_difference = FiniteDifference(order=2)
np.testing.assert_allclose(centered_difference(x, t), x_dot, atol=1e-8)
def test_centered_difference_xy_yx(data_2dspatial):
x_grid, y_grid, u = data_2dspatial
u_xy = np.zeros(u.shape)
u_yx = np.zeros(u.shape)
u_y = FiniteDifference(order=2, d=1, axis=1)._differentiate(u, y_grid)
u_x = FiniteDifference(order=2, d=1, axis=0)._differentiate(u, x_grid)
u_xy = FiniteDifference(order=2, d=1, axis=1)._differentiate(u_x, y_grid)
u_yx = FiniteDifference(order=2, d=1, axis=0)._differentiate(u_y, x_grid)
np.testing.assert_allclose(u_xy, u_yx)
u_y = FiniteDifference(order=1, d=1, axis=1)._differentiate(u, y_grid)
u_x = FiniteDifference(order=1, d=1, axis=0)._differentiate(u, x_grid)
u_xy = FiniteDifference(order=1, d=1, axis=1)._differentiate(u_x, y_grid)
u_yx = FiniteDifference(order=1, d=1, axis=0)._differentiate(u_y, x_grid)
np.testing.assert_allclose(u_xy, u_yx)
def test_centered_difference_hot(data_derivative_2d):
x, _ = data_derivative_2d
t = np.linspace(0, x.shape[0], x.shape[0])
dt = t[1] - t[0]
atol = 1e-8
for d in range(1, 2):
forward_difference = FiniteDifference(order=1, d=d)._differentiate
np.testing.assert_allclose(
forward_difference(x, t=dt),
forward_difference(x, t=t),
atol=atol,
)
for d in range(1, 6):
centered_difference = FiniteDifference(order=2, d=d)._differentiate
np.testing.assert_allclose(
centered_difference(x, t=dt),
centered_difference(x, t=t),
atol=atol,
)
for d in range(1, 6):
spectral_deriv = SpectralDerivative(d=d)._differentiate
np.testing.assert_allclose(
spectral_deriv(x, t=dt),
spectral_deriv(x, t=t),
atol=atol,
)
# Alternative implementation of the four tests above using parametrization
@pytest.mark.parametrize(
"data, order",
[
(pytest.lazy_fixture("data_derivative_1d"), 2),
(pytest.lazy_fixture("data_derivative_2d"), 2),
(pytest.lazy_fixture("data_derivative_1d"), 4),
(pytest.lazy_fixture("data_derivative_2d"), 4),
(pytest.lazy_fixture("data_derivative_1d"), 8),
(pytest.lazy_fixture("data_derivative_2d"), 8),
],
)
def test_finite_difference(data, order):
x, x_dot = data
method = FiniteDifference(order=order)
np.testing.assert_allclose(method(x), x_dot)
method = SmoothedFiniteDifference()
np.testing.assert_allclose(method(x), x_dot)
def test_order_error():
with pytest.raises(ValueError):
FiniteDifference(order=-1)
with pytest.raises(ValueError):
FiniteDifference(d=-1)
with pytest.raises(ValueError):
FiniteDifference(d=2, order=1)
with pytest.raises(ValueError):
FiniteDifference(d=1, order=0.5)
with pytest.raises(ValueError):
FiniteDifference(d=1, order=0)
with pytest.raises(ValueError):
FiniteDifference(d=0, order=1)
def test_base_class(data_derivative_1d):
x, x_dot = data_derivative_1d
with pytest.raises(NotImplementedError):
BaseDifferentiation()._differentiate(x)
# Test smoothed finite difference method
@pytest.mark.parametrize(
"data",
[
pytest.lazy_fixture("data_derivative_1d"),
pytest.lazy_fixture("data_derivative_2d"),
],
)
def test_smoothed_finite_difference(data):
x, x_dot = data
smoothed_centered_difference = SmoothedFiniteDifference()
np.testing.assert_allclose(smoothed_centered_difference(x), x_dot)
@pytest.mark.parametrize(
"data, derivative_kws",
[
(pytest.lazy_fixture("data_derivative_1d"), dict(kind="spectral")),
(pytest.lazy_fixture("data_derivative_2d"), dict(kind="spectral")),
(pytest.lazy_fixture("data_derivative_1d"), dict(kind="spline", s=1e-2)),
(pytest.lazy_fixture("data_derivative_2d"), dict(kind="spline", s=1e-2)),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="trend_filtered", order=0, alpha=1e-2),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="trend_filtered", order=0, alpha=1e-2),
),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="finite_difference", k=1),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="finite_difference", k=1),
),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="savitzky_golay", order=3, left=1, right=1),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="savitzky_golay", order=3, left=1, right=1),
),
],
)
def test_wrapper_equivalence_with_dxdt(data, derivative_kws):
x, _ = data
t = np.arange(x.shape[0])
if np.ndim(x) == 1:
np.testing.assert_allclose(
dxdt(x, t, axis=0, **derivative_kws),
SINDyDerivative(**derivative_kws)(x, t),
)
else:
np.testing.assert_allclose(
dxdt(x, t, axis=0, **derivative_kws),
SINDyDerivative(**derivative_kws)(x, t),
)
def test_sindy_derivative_kwarg_update():
method = SINDyDerivative(kind="spectral", foo=2)
method.set_params(kwargs={"kind": "spline", "foo": 1})
assert method.kwargs["kind"] == "spline"
assert method.kwargs["foo"] == 1
@pytest.mark.parametrize(
"data, derivative_kws",
[
(pytest.lazy_fixture("data_derivative_1d"), dict(kind="spectral")),
(pytest.lazy_fixture("data_derivative_2d"), dict(kind="spectral")),
(pytest.lazy_fixture("data_derivative_1d"), dict(kind="spline", s=1e-2)),
(pytest.lazy_fixture("data_derivative_2d"), dict(kind="spline", s=1e-2)),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="trend_filtered", order=0, alpha=1e-2),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="trend_filtered", order=0, alpha=1e-2),
),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="finite_difference", k=1),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="finite_difference", k=1),
),
(
pytest.lazy_fixture("data_derivative_1d"),
dict(kind="savitzky_golay", order=3, left=1, right=1),
),
(
pytest.lazy_fixture("data_derivative_2d"),
dict(kind="savitzky_golay", order=3, left=1, right=1),
),
],
)
def test_derivative_output_shape(data, derivative_kws):
x, x_dot = data
t = np.arange(x.shape[0])
method = SINDyDerivative(**derivative_kws)
assert x_dot.shape == method(x).shape
assert x_dot.shape == method(x, t).shape
def test_bad_t_values(data_derivative_1d):
x, x_dot = data_derivative_1d
method = SINDyDerivative(kind="finite_difference", k=1)
with pytest.raises(ValueError):
method(x, t=-1)
with pytest.raises(ValueError):
method._differentiate(x, t=-1)
def test_centered_difference_hot_axis(data_2d_resolved_pde):
_, u_flat, u_dot_flat = data_2d_resolved_pde
x = np.reshape(u_flat, (8, 8, 1000, 2))
t = np.linspace(0, 10, 1000)
dt = t[1] - t[0]
atol = 1e-8
for d in range(1, 2):
forward_difference = FiniteDifference(order=1, d=d, axis=-2)._differentiate
np.testing.assert_allclose(
forward_difference(x, t=dt),
forward_difference(x, t=t),
atol=atol,
)
for d in range(1, 6):
centered_difference = FiniteDifference(order=2, d=d, axis=-2)._differentiate
np.testing.assert_allclose(
centered_difference(x, t=dt),
centered_difference(x, t=t),
atol=atol,
)
for d in range(1, 6):
spectral_deriv = SpectralDerivative(d=d, axis=-2)._differentiate
np.testing.assert_allclose(
spectral_deriv(x, t=dt),
spectral_deriv(x, t=t),
atol=atol,
)
def test_centered_difference_noaxis_vs_axis(data_2d_resolved_pde):
_, u_flat, u_dot_flat = data_2d_resolved_pde
n = 8
x = np.reshape(u_flat, (n, n, 1000, 2))
t = np.linspace(0, 10, 1000)
dt = t[1] - t[0]
atol = 1e-10
for d in range(1, 6):
centered_difference = FiniteDifference(order=2, d=d, axis=-2)._differentiate
slow_differences = np.zeros(x.shape)
slow_differences_t = np.zeros(x.shape)
for i in range(n):
for j in range(n):
slow_differences[i, j, :, :] = FiniteDifference(
order=2, d=d
)._differentiate(x[i, j, :, :], t=dt)
slow_differences_t[i, j, :, :] = FiniteDifference(
order=2, d=d
)._differentiate(x[i, j, :, :], t=t)
np.testing.assert_allclose(
centered_difference(x, t=dt),
slow_differences,
atol=atol,
)
np.testing.assert_allclose(
centered_difference(x, t=t),
slow_differences_t,
atol=atol,
)