Download data/data_utils.py from gundo0102/SleepMaMi: direct link, hf CLI and curl.
- Browser
- Download file 2.64 kB
-
https://huggingface.co/gundo0102/SleepMaMi/resolve/main/data/data_utils.py
- Command line
-
hf download hf://gundo0102/SleepMaMi/data/data_utils.py
-
curl -L -o data_utils.py https://huggingface.co/gundo0102/SleepMaMi/resolve/main/data/data_utils.py
2.64 kB
| import os | |
| import numpy as np | |
| from scipy.signal import butter, sosfilt, lfilter, iirnotch | |
| from scipy.signal import find_peaks | |
| def butter_bandpass(lowcut, highcut, fs, order=8): | |
| low = lowcut | |
| high = highcut | |
| sos = butter(order, [low, high], btype='band', fs=fs, output='sos', analog=False) | |
| return sos | |
| def butter_highpass(lowcut, fs, order=8): | |
| low = lowcut | |
| sos = butter(order, low, btype='highpass', fs=fs, output='sos', analog=False) | |
| return sos | |
| def butter_lowpass(highcut, fs, order=8): | |
| high = highcut | |
| sos = butter(order, high, btype='lowpass', fs=fs, output='sos', analog=False) | |
| return sos | |
| def butter_bandpass_filter(data, lowcut, highcut, fs, order=8): | |
| if highcut > fs/2: | |
| sos = butter_highpass(lowcut, fs, order=order) | |
| elif lowcut <= 0: | |
| sos = butter_lowpass(highcut, fs, order=order) | |
| else: | |
| sos = butter_bandpass(lowcut, highcut, fs, order=order) | |
| #y = lfilter(b, a, data) | |
| y = sosfilt(sos, data) | |
| return y | |
| def correct_ecg_inversion(ecg_signal, sampling_rate): | |
| """ | |
| ECG ์ ํธ๊ฐ ๋ค์งํ๋์ง ๊ฐ์งํ๊ณ ์ฌ๋ฐ๋ฅด๊ฒ ์์ ํฉ๋๋ค. | |
| Args: | |
| ecg_signal (np.array): ECG ์ ํธ ๋ฐ์ดํฐ. | |
| sampling_rate (int): ์ํ๋ง ์ฃผํ์ (Hz). | |
| Returns: | |
| np.array: ์์ ๋ ECG ์ ํธ. | |
| bool: ๋ค์งํ์ด ๊ฐ์ง๋์๋์ง ์ฌ๋ถ. | |
| """ | |
| # QRS๊ตฐ์ Rํ๋ฅผ ์ฐพ๊ธฐ ์ํด ์ ํธ์ ์์ ํผํฌ๋ฅผ ์ฐพ์ | |
| # prominence: ํผํฌ๊ฐ ์ฃผ๋ณ๋ณด๋ค ์ผ๋ง๋ ํ์ด๋์๋์ง, distance: ํผํฌ ๊ฐ ์ต์ ๊ฑฐ๋ฆฌ | |
| positive_peaks, _ = find_peaks(ecg_signal, prominence=0.1, distance=0.3 * sampling_rate) | |
| # QRS๊ตฐ์ Sํ(๋ค์งํ Rํ)๋ฅผ ์ฐพ๊ธฐ ์ํด ์ ํธ๋ฅผ ๋ค์ง์ด์ ํผํฌ๋ฅผ ์ฐพ์ | |
| negative_peaks, _ = find_peaks(-ecg_signal, prominence=0.1, distance=0.3 * sampling_rate) | |
| # ํผํฌ๊ฐ ํ๋๋ ๊ฐ์ง๋์ง ์์ผ๋ฉด ์๋ณธ ์ ํธ ๋ฐํ | |
| if len(positive_peaks) == 0 and len(negative_peaks) == 0: | |
| return ecg_signal, False | |
| # ์์ ํผํฌ์ ์์ ํผํฌ์ ํ๊ท ์งํญ ๊ณ์ฐ | |
| mean_pos_amp = np.mean(ecg_signal[positive_peaks]) if len(positive_peaks) > 0 else 0 | |
| mean_neg_amp = np.mean(ecg_signal[negative_peaks]) if len(negative_peaks) > 0 else 0 | |
| # ๋ง์ฝ ์์ ํผํฌ์ ์ ๋๊ฐ์ด ์์ ํผํฌ๋ณด๋ค ํฌ๋ฉด ๋ค์งํ ๊ฒ์ผ๋ก ํ๋จ | |
| is_inverted = abs(mean_neg_amp) > abs(mean_pos_amp) | |
| if is_inverted: | |
| # print("๐ก ECG ์ ํธ๊ฐ ๋ค์งํ ๊ฒ์ ๊ฐ์งํ์ฌ ์์ ํฉ๋๋ค.") | |
| return ecg_signal * -1, True | |
| else: | |
| # print("โ ECG ์ ํธ๊ฐ ์ ์ ๋ฐฉํฅ์ ๋๋ค.") | |
| return ecg_signal, False |