Last active
September 13, 2022 13:12
-
-
Save adrianomitre/2ced5544421eca031180782cc30798af to your computer and use it in GitHub Desktop.
Hampel filter implementation in Python using numba
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on https://gist.github.com/erykml/9b07b916ceee78c207d14fa2548b8f6f#file-hampel_filter_forloop_numba-py | |
import numpy as np | |
from numba import jit | |
@jit(nopython=True) | |
def hampel_filter_forloop_numba(input_series, window_length, n_sigmas=3): | |
if window_length % 2 == 0: | |
raise ValueError('window_length should be odd') | |
h = int(window_length/2) | |
n = len(input_series) | |
new_series = input_series.copy() | |
k = 1.4826022185056018 # scale factor for Gaussian distribution | |
indices = [] | |
for i in range((h),(n - h + 1)): | |
x0 = np.nanmedian(input_series[(i - h):(i + h + 1)]) | |
S0 = k * np.nanmedian(np.abs(input_series[(i - h):(i + h + 1)] - x0)) | |
if (np.abs(input_series[i] - x0) > n_sigmas * S0): | |
new_series[i] = x0 | |
indices.append(i) | |
return new_series, indices |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment