Search code examples
pythonrscipydifferentiation

Utilising Savitzky-Golay Filter in R vs Python


I'm currently trying to render the same results in R as in Python but think I must be misunderstanding the Savitzky-Golay filter. I have the below Python code:

import numpy as np
from scipy.signal import savgol_filter
t = np.linspace(0,1,10)
X = np.vstack((np.sin(t),np.cos(t))).T
sfd = savgol_filter(X, window_length=5, polyorder=3, axis=0)
sfd
array([[-4.78900581e-07,  9.99997881e-01],
       [ 1.10884544e-01,  9.93841986e-01],
       [ 2.20394870e-01,  9.75397369e-01],
       [ 3.27190431e-01,  9.44944627e-01],
       [ 4.29950758e-01,  9.02837899e-01],
       [ 5.27408510e-01,  8.49596486e-01],
       [ 6.18361741e-01,  7.85877015e-01],
       [ 7.01688728e-01,  7.12465336e-01],
       [ 7.76378020e-01,  6.30281243e-01],
       [ 8.41469460e-01,  5.40300758e-01]])

From my understanding, this smooths the matrix and prepares it to develop the derivative term. However, when using pracma in R (the most recently updated version of a Savitzky-Golay function), I get:

library(pracma)
t = seq(0, 1,length = 10)
X = t(rbind(sin(t), cos(t)))
savgol(X[, 1], fl = 5)
[1] 1.229175e-16 1.108826e-01 2.203977e-01 3.271947e-01 4.299564e-01 5.274154e-01 6.183698e-01 7.016979e-01 7.763719e-01 8.414710e-01

Does anyone know why these numbers are so different and how I can produce the same results from Python in R?

Thanks in advance.


Solution

  • Use the sgolayfilt function in the signal package:

    library(signal)
    packageVersion("signal")
    ## [1] ‘0.7.7’
    
    apply(X, 2, sgolayfilt, n = 5)
    ##                [,1]      [,2]
    ##  [1,] -4.789006e-07 0.9999979
    ##  [2,]  1.108845e-01 0.9938420
    ##  [3,]  2.203949e-01 0.9753974
    ##  [4,]  3.271904e-01 0.9449446
    ##  [5,]  4.299508e-01 0.9028379
    ##  [6,]  5.274085e-01 0.8495965
    ##  [7,]  6.183617e-01 0.7858770
    ##  [8,]  7.016887e-01 0.7124653
    ##  [9,]  7.763780e-01 0.6302812
    ## [10,]  8.414695e-01 0.5403008