File size: 4,605 Bytes
854b533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import numpy as np
import pywt
import os
from scipy.signal import butter, filtfilt, iirnotch, medfilt, find_peaks
import matplotlib.pyplot as plt
# 1. Load the Data

print("Loading datasets...")
data_train = np.load("X_train.npy")
data_valid = np.load("X_val.npy")
data_test = np.load("X_test.npy")

print("\n--- Dataset Shapes ---")
print(f"Train data shape: {data_train.shape}")
print(f"Validation data shape: {data_valid.shape}")
print(f"Test data shape: {data_test.shape}")
print("----------------------\n")

os.mkdir("filtered_data")

# 2. Define the Processing Functions
def _remove_baseline_wander(ecg_signal, wavelet='sym8'):
    desired  = int(np.ceil(np.log2(100/0.5)))
    max_level = pywt.dwt_max_level(len(ecg_signal), pywt.Wavelet(wavelet).dec_len)
    level =  min(desired, max_level)
    
    coeffs = pywt.wavedec(ecg_signal, wavelet, level=level)
    coeffs_filt = [coeffs[0]] + [np.zeros_like(c) for c in coeffs[1:]]
    
    baseline = pywt.waverec(coeffs_filt, wavelet)
    baseline = baseline[:len(ecg_signal)]
    
    return ecg_signal - baseline

def _denoise(data):
    # Wavelet transform
    coeffs = pywt.wavedec(data=data, wavelet='db5', level=9)
    cA9, cD9, cD8, cD7, cD6, cD5, cD4, cD3, cD2, cD1 = coeffs

    # Threshold denoising
    threshold = (np.median(np.abs(cD1)) / 0.6745) * (np.sqrt(2 * np.log(len(cD1))))
    cD1.fill(0)
    cD2.fill(0)
    
    for i in range(1, len(coeffs) - 2):
        coeffs[i] = pywt.threshold(coeffs[i], threshold)

    # Inverse wavelet transform to obtain the denoised signal
    rdata = pywt.waverec(coeffs=coeffs, wavelet='db5')
    return rdata

def remove_noise_and_wander(data):
    baseline_wander = _remove_baseline_wander(data)
    cleaned = _denoise(baseline_wander)
    return cleaned

# 3. Apply the Filter
# Assuming your data shape is (num_samples, signal_length). 
# If it's a 1D array of a single continuous signal, remove the list comprehension loop.
def process_batch(dataset_array):
    print(f"Processing {len(dataset_array)} samples...")
    # Applies the cleaning function to each row/signal in the array
    return [remove_noise_and_wander(signal) for signal in dataset_array]

print("\nFiltering Train Data...")
train_filtered = process_batch(data_train)

print("Filtering Validation Data...")
valid_filtered = process_batch(data_valid)

print("Filtering Test Data...")
test_filtered = process_batch(data_test)

np.save("filtered_data/X_train_filtered.npy", train_filtered)
np.save("filtered_data/X_val_filtered.npy", valid_filtered)
np.save("filtered_data/X_test_filtered.npy", test_filtered)


print("Loading data...")
data_train_new = np.load("filtered_data/X_train_filtered.npy")
data_valid_new = np.load("filtered_data/X_val_filtered.npy")
data_test_new = np.load("filtered_data/X_test_filtered.npy")

print("\n--- Dataset Shapes ---")
print(f"Train data shape: {data_train_new.shape}")
print(f"Validation data shape: {data_valid_new.shape}")
print(f"Test data shape: {data_test_new.shape}")
print("----------------------\n")


# --- 3. Plot 5 Samples Before and After ---
# We assume data_train is a 2D array of shape (num_samples, signal_length)
num_samples_to_plot = 5

# Create a figure with 5 rows and 2 columns
fig, axes = plt.subplots(nrows=num_samples_to_plot, ncols=2, figsize=(16, 12))
fig.suptitle('ECG Signal Processing: Before vs. After', fontsize=18, fontweight='bold')

for i in range(num_samples_to_plot):
    # Get the original 1D signal for the i-th sample
    original_signal = data_train_new[i]
    
    # Process the signal
    filtered_signal = remove_noise_and_wander(original_signal)
    
    # Plot Original (Before) - Left Column
    axes[i, 0].plot(original_signal, color='crimson', linewidth=1)
    axes[i, 0].set_title(f"Sample {i+1}: Original (Raw)")
    axes[i, 0].set_ylabel("Amplitude")
    axes[i, 0].grid(True, linestyle='--', alpha=0.6)
    
    # Plot Filtered (After) - Right Column
    axes[i, 1].plot(filtered_signal, color='navy', linewidth=1)
    axes[i, 1].set_title(f"Sample {i+1}: Filtered (Denoised & Baseline Removed)")
    axes[i, 1].grid(True, linestyle='--', alpha=0.6)
    
    # Only show x-axis label for the bottom-most plots to keep it clean
    if i == num_samples_to_plot - 1:
        axes[i, 0].set_xlabel("Time steps")
        axes[i, 1].set_xlabel("Time steps")

# Adjust layout so titles and labels don't overlap
plt.tight_layout(rect=[0, 0.03, 1, 0.96])

# Save the figure as a high-resolution PNG
plt.savefig("ecg_filtering_results.png", dpi=300, bbox_inches='tight')
print("Image saved successfully as 'ecg_filtering_results.png'")
plt.show()