Skip to content

Instantly share code, notes, and snippets.

@gelez
Created November 7, 2017 19:08
Show Gist options
  • Save gelez/2bd4441558749a473d35c1a8ef458fda to your computer and use it in GitHub Desktop.
Save gelez/2bd4441558749a473d35c1a8ef458fda to your computer and use it in GitHub Desktop.
Python implementation Tarvainen et.al. "An Advanced Detrending Method With Application to HRV Analysis"
def tarvainen_filter(sig, lam):
""" Returns detrended signal
Keyword arguments:
sig - input signal (1d array)
lam - smoothing parameter(lambda)
The implementation of
"An Advanced Detrending Method With Application to HRV Analysis"
Mika P. Tarvainen, Perttu O. Ranta-aho, and Pasi A. Karjalainen
IEEE TRANSACTIONS ON BIOMEDICAL ENGINEERING, VOL. 49, NO. 2, FEBRUARY 2002
It is the same method as method:
W. Gersch, Smoothness priors , in New Directions in Time Series , Analysis, Part II, pp. 113-146.
Springer-Verlag, 1991.
Matlab implementation
N=100; % Number of points
x=randn(N,1); % Random data
T = length(x);
lambda = 100;
I = speye(T);
D2 = spdiags(ones(T-2,1)[1 -2 1], [0:2], T-2, T);
xhat = (I-inv(I+lambda^2D2'D2))x
figure()
plot(1:N,x,'b',1:N,xhat,'k')
Code written by Konstantin Purtov <k.s.purtov@gmail.com> 2015
example of using:
signal_with_noise = np.random.rand(200)
detrended_signal = tarvainen_filter(signal_with_noise, 2000)
"""
import numpy as np
import scipy.sparse
sig = np.array(sig)
T = len(sig)
I = np.identity(T)
filt = [1, -2, 1] * np.ones((1, T), dtype=np.int).T
D2 = scipy.sparse.spdiags(filt.T, (range(0, 3)), T - 2, T).toarray()
xhat = np.dot((I - np.linalg.inv(I + (lam ** 2) * np.dot(D2.T, D2))), sig) # filtered signal
return xhat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment