Skip to content

Instantly share code, notes, and snippets.

@judges119
Last active November 10, 2020 18:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judges119/24e4ac8b0e4a988a9d45 to your computer and use it in GitHub Desktop.
Save judges119/24e4ac8b0e4a988a9d45 to your computer and use it in GitHub Desktop.
JS Hampel Filter
/*
Hampel Filter implemented in JavaScript by Adam O'Grady
AN: Very basic (ie: improve before using in production) function I needed for some work stuff, used for detecting and removing outliers in a moving window via Median Absolute Deviation (MAD)
PARAMS:
data - Array of numbers to be examined
half_window: Integer representing half the moving window size to use
threshold: Integer for the maximum multiple of the Median Absolute Deviation before it's considered an outlier and replaced with the median
RETURNS:
object:
data: updated, smoothed array
ind: original indicies of removed outliers
*/
function hampelFilter(data, half_window, threshold) {
if (typeof threshold === 'undefined') {
threshold = 3;
}
var n = data.length;
var data_copy = data;
var ind = [];
var L = 1.4826;
for (var i = half_window + 1; i < n - half_window; i++) {
var med = median(data.slice(i - half_window, i + half_window));
var MAD = L * median(data.slice(i - half_window, i + half_window).map(function(e) { return Math.abs(e - med) }));
if (Math.abs(data[i] - med) / MAD > threshold) {
data_copy[i] = med;
ind = ind.concat(i);
}
}
return {
data: data_copy,
outliers: ind
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment