Skip to content

Instantly share code, notes, and snippets.

@antonior92
Created February 15, 2021 21:05
Show Gist options
  • Save antonior92/b5cd0995b7e5e3e81867571a7e613167 to your computer and use it in GitHub Desktop.
Save antonior92/b5cd0995b7e5e3e81867571a7e613167 to your computer and use it in GitHub Desktop.
from scipy.signal import decimate, resample_poly
def resample_ecg(trace, input_freq, output_freq, axis=-1):
"""Resample ecg.
`trace` should be a multidimensional numpy array. `axis` gives which axis will be resampled (be default the last
one). `input_freq` and `output_freq` are the input and output frequency (in heartz). Use the most appropriate SciPy
function vailable: first try decimate (with bidirectional filtering), if the input and output frequencies are not
multiple, it resamples using polyphase filtering.
"""
trace = np.atleast_1d(trace).astype(float)
if input_freq != int(input_freq):
raise ValueError("input_freq must be an integer")
if output_freq != int(output_freq):
raise ValueError("output_freq must be an integer")
if input_freq == output_freq:
new_trace = trace
elif np.mod(input_freq, output_freq) == 0:
new_trace = decimate(trace, q=input_freq//output_freq,
ftype='iir', zero_phase=True, axis=axis)
else:
new_trace = resample_poly(trace, up=output_freq, down=input_freq, axis=axis)
return new_trace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment