File: test_savitzky_golay.py

package info (click to toggle)
python-scipy 0.18.1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 75,464 kB
  • ctags: 79,406
  • sloc: python: 143,495; cpp: 89,357; fortran: 81,650; ansic: 79,778; makefile: 364; sh: 265
file content (294 lines) | stat: -rw-r--r-- 9,924 bytes parent folder | download
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
from __future__ import division, print_function, absolute_import

import numpy as np
from numpy.testing import (run_module_suite, assert_allclose, assert_equal,
                           assert_almost_equal, assert_array_equal,
                           assert_array_almost_equal)

from scipy.ndimage import convolve1d

from scipy.signal import savgol_coeffs, savgol_filter
from scipy.signal._savitzky_golay import _polyder


def check_polyder(p, m, expected):
    dp = _polyder(p, m)
    assert_array_equal(dp, expected)


def test_polyder():
    cases = [
        ([5], 0, [5]),
        ([5], 1, [0]),
        ([3, 2, 1], 0, [3, 2, 1]),
        ([3, 2, 1], 1, [6, 2]),
        ([3, 2, 1], 2, [6]),
        ([3, 2, 1], 3, [0]),
        ([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]),
        ([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]),
        ([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]),
        ([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]),
    ]
    for p, m, expected in cases:
        yield check_polyder, np.array(p).T, m, np.array(expected).T


#--------------------------------------------------------------------
# savgol_coeffs tests
#--------------------------------------------------------------------

def alt_sg_coeffs(window_length, polyorder, pos):
    """This is an alternative implementation of the SG coefficients.

    It uses numpy.polyfit and numpy.polyval.  The results should be
    equivalent to those of savgol_coeffs(), but this implementation
    is slower.

    window_length should be odd.

    """
    if pos is None:
        pos = window_length // 2
    t = np.arange(window_length)
    unit = (t == pos).astype(int)
    h = np.polyval(np.polyfit(t, unit, polyorder), t)
    return h


def test_sg_coeffs_trivial():
    # Test a trivial case of savgol_coeffs: polyorder = window_length - 1
    h = savgol_coeffs(1, 0)
    assert_allclose(h, [1])

    h = savgol_coeffs(3, 2)
    assert_allclose(h, [0, 1, 0], atol=1e-10)

    h = savgol_coeffs(5, 4)
    assert_allclose(h, [0, 0, 1, 0, 0], atol=1e-10)

    h = savgol_coeffs(5, 4, pos=1)
    assert_allclose(h, [0, 0, 0, 1, 0], atol=1e-10)

    h = savgol_coeffs(5, 4, pos=1, use='dot')
    assert_allclose(h, [0, 1, 0, 0, 0], atol=1e-10)


def compare_coeffs_to_alt(window_length, order):
    # For the given window_length and order, compare the results
    # of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1.
    # Also include pos=None.
    for pos in [None] + list(range(window_length)):
        h1 = savgol_coeffs(window_length, order, pos=pos, use='dot')
        h2 = alt_sg_coeffs(window_length, order, pos=pos)
        assert_allclose(h1, h2, atol=1e-10,
                        err_msg=("window_length = %d, order = %d, pos = %s" %
                                 (window_length, order, pos)))


def test_sg_coeffs_compare():
    # Compare savgol_coeffs() to alt_sg_coeffs().
    for window_length in range(1, 8, 2):
        for order in range(window_length):
            yield compare_coeffs_to_alt, window_length, order


def test_sg_coeffs_exact():
    polyorder = 4
    window_length = 9
    halflen = window_length // 2

    x = np.linspace(0, 21, 43)
    delta = x[1] - x[0]

    # The data is a cubic polynomial.  We'll use an order 4
    # SG filter, so the filtered values should equal the input data
    # (except within half window_length of the edges).
    y = 0.5 * x ** 3 - x
    h = savgol_coeffs(window_length, polyorder)
    y0 = convolve1d(y, h)
    assert_allclose(y0[halflen:-halflen], y[halflen:-halflen])

    # Check the same input, but use deriv=1.  dy is the exact result.
    dy = 1.5 * x ** 2 - 1
    h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta)
    y1 = convolve1d(y, h)
    assert_allclose(y1[halflen:-halflen], dy[halflen:-halflen])

    # Check the same input, but use deriv=2. d2y is the exact result.
    d2y = 3.0 * x
    h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta)
    y2 = convolve1d(y, h)
    assert_allclose(y2[halflen:-halflen], d2y[halflen:-halflen])


def test_sg_coeffs_deriv():
    # The data in `x` is a sampled parabola, so using savgol_coeffs with an
    # order 2 or higher polynomial should give exact results.
    i = np.array([-2.0, 0.0, 2.0, 4.0, 6.0])
    x = i ** 2 / 4
    dx = i / 2
    d2x = 0.5 * np.ones_like(i)
    for pos in range(x.size):
        coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot')
        assert_allclose(coeffs0.dot(x), x[pos], atol=1e-10)
        coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1)
        assert_allclose(coeffs1.dot(x), dx[pos], atol=1e-10)
        coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2)
        assert_allclose(coeffs2.dot(x), d2x[pos], atol=1e-10)


def test_sg_coeffs_large():
    # Test that for large values of window_length and polyorder the array of
    # coefficients returned is symmetric. The aim is to ensure that
    # no potential numeric overflow occurs.
    coeffs0 = savgol_coeffs(31, 9)
    assert_array_almost_equal(coeffs0, coeffs0[::-1])
    coeffs1 = savgol_coeffs(31, 9, deriv=1)
    assert_array_almost_equal(coeffs1, -coeffs1[::-1])


#--------------------------------------------------------------------
# savgol_filter tests
#--------------------------------------------------------------------


def test_sg_filter_trivial():
    """ Test some trivial edge cases for savgol_filter()."""
    x = np.array([1.0])
    y = savgol_filter(x, 1, 0)
    assert_equal(y, [1.0])

    # Input is a single value.  With a window length of 3 and polyorder 1,
    # the value in y is from the straight-line fit of (-1,0), (0,3) and
    # (1, 0) at 0. This is just the average of the three values, hence 1.0.
    x = np.array([3.0])
    y = savgol_filter(x, 3, 1, mode='constant')
    assert_almost_equal(y, [1.0], decimal=15)

    x = np.array([3.0])
    y = savgol_filter(x, 3, 1, mode='nearest')
    assert_almost_equal(y, [3.0], decimal=15)

    x = np.array([1.0] * 3)
    y = savgol_filter(x, 3, 1, mode='wrap')
    assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15)


def test_sg_filter_basic():
    # Some basic test cases for savgol_filter().
    x = np.array([1.0, 2.0, 1.0])
    y = savgol_filter(x, 3, 1, mode='constant')
    assert_allclose(y, [1.0, 4.0 / 3, 1.0])

    y = savgol_filter(x, 3, 1, mode='mirror')
    assert_allclose(y, [5.0 / 3, 4.0 / 3, 5.0 / 3])

    y = savgol_filter(x, 3, 1, mode='wrap')
    assert_allclose(y, [4.0 / 3, 4.0 / 3, 4.0 / 3])


def test_sg_filter_2d():
    x = np.array([[1.0, 2.0, 1.0],
                  [2.0, 4.0, 2.0]])
    expected = np.array([[1.0, 4.0 / 3, 1.0],
                         [2.0, 8.0 / 3, 2.0]])
    y = savgol_filter(x, 3, 1, mode='constant')
    assert_allclose(y, expected)

    y = savgol_filter(x.T, 3, 1, mode='constant', axis=0)
    assert_allclose(y, expected.T)


def test_sg_filter_interp_edges():
    # Another test with low degree polynomial data, for which we can easily
    # give the exact results.  In this test, we use mode='interp', so
    # savgol_filter should match the exact solution for the entire data set,
    # including the edges.
    t = np.linspace(-5, 5, 21)
    delta = t[1] - t[0]
    # Polynomial test data.
    x = np.array([t,
                  3 * t ** 2,
                  t ** 3 - t])
    dx = np.array([np.ones_like(t),
                   6 * t,
                   3 * t ** 2 - 1.0])
    d2x = np.array([np.zeros_like(t),
                    6 * np.ones_like(t),
                    6 * t])

    window_length = 7

    y = savgol_filter(x, window_length, 3, axis=-1, mode='interp')
    assert_allclose(y, x, atol=1e-12)

    y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
                       deriv=1, delta=delta)
    assert_allclose(y1, dx, atol=1e-12)

    y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
                       deriv=2, delta=delta)
    assert_allclose(y2, d2x, atol=1e-12)

    # Transpose everything, and test again with axis=0.

    x = x.T
    dx = dx.T
    d2x = d2x.T

    y = savgol_filter(x, window_length, 3, axis=0, mode='interp')
    assert_allclose(y, x, atol=1e-12)

    y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
                       deriv=1, delta=delta)
    assert_allclose(y1, dx, atol=1e-12)

    y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
                       deriv=2, delta=delta)
    assert_allclose(y2, d2x, atol=1e-12)


def test_sg_filter_interp_edges_3d():
    # Test mode='interp' with a 3-D array.
    t = np.linspace(-5, 5, 21)
    delta = t[1] - t[0]
    x1 = np.array([t, -t])
    x2 = np.array([t ** 2, 3 * t ** 2 + 5])
    x3 = np.array([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t])
    dx1 = np.array([np.ones_like(t), -np.ones_like(t)])
    dx2 = np.array([2 * t, 6 * t])
    dx3 = np.array([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5])

    # z has shape (3, 2, 21)
    z = np.array([x1, x2, x3])
    dz = np.array([dx1, dx2, dx3])

    y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta)
    assert_allclose(y, z, atol=1e-10)

    dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta)
    assert_allclose(dy, dz, atol=1e-10)

    # z has shape (3, 21, 2)
    z = np.array([x1.T, x2.T, x3.T])
    dz = np.array([dx1.T, dx2.T, dx3.T])

    y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta)
    assert_allclose(y, z, atol=1e-10)

    dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta)
    assert_allclose(dy, dz, atol=1e-10)

    # z has shape (21, 3, 2)
    z = z.swapaxes(0, 1).copy()
    dz = dz.swapaxes(0, 1).copy()

    y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta)
    assert_allclose(y, z, atol=1e-10)

    dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta)
    assert_allclose(dy, dz, atol=1e-10)


if __name__ == "__main__":
    run_module_suite()