Spaces:
Sleeping
Sleeping
File size: 2,935 Bytes
8b33ce3 f91d7d1 f52d1e7 f91d7d1 | 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 | import pandas as pd
import numpy as np
# Preprocesing Function
def preprocess_eeg(csv_file, window_size=200, stride=100):
"""
Preprocess EEG CSV for model inference with artifact removal.
Steps:
1. Load CSV.
2. Keep only 'timestampMs' and 'eegRawValueVolts'.
3. Remove rows with poorSignal > 52 or blinkStrength > 100.
4. Create uniform 10ms timestamp grid.
5. Interpolate missing EEG values.
6. Z-score normalize the EEG signal.
7. Window the signal into overlapping segments.
Parameters:
csv_file: file object or path to CSV
window_size: number of samples per window (default 200 → 2s @100Hz)
stride: step size between windows (default 100 → 50% overlap)
Returns:
X_windows: np.array of shape (num_windows, window_size, 1)
window_timestamps: np.array of timestamps corresponding to each window start
"""
# 1. Load CSV
df = pd.read_csv(csv_file)
# --- ADD THESE LINES ---
# Normalize timestampMs to start at 0
first_ts = df['timestampMs'].iloc[0]
df['timestampMs'] = df['timestampMs'] - first_ts
# --- END ADD ---
# 2. Remove artifact rows
if 'poorSignal' in df.columns:
df = df[df['poorSignal'] <= 52]
if 'blinkStrength' in df.columns:
df = df[df['blinkStrength'] <= 100]
# 3. Keep only necessary columns
if 'timestampMs' not in df.columns or 'eegRawValueVolts' not in df.columns:
raise ValueError("CSV must contain 'timestampMs' and 'eegRawValueVolts' columns")
df = df[['timestampMs', 'eegRawValueVolts']].copy()
# 4. Create uniform 10ms grid
ts_min, ts_max = df['timestampMs'].min(), df['timestampMs'].max()
ts_grid = np.arange(ts_min, ts_max + 10, 10) # inclusive of last timestamp
df_grid = pd.DataFrame({'timestampMs': ts_grid})
# Merge original values onto uniform grid
df_merged = pd.merge(df_grid, df, on='timestampMs', how='left')
# 5. Interpolate missing values
df_merged['eegRawValueVolts'] = df_merged['eegRawValueVolts'].interpolate(method='linear', limit_direction='both')
# 6. Z-score normalization
eeg_signal = df_merged['eegRawValueVolts'].values
eeg_signal = (eeg_signal - np.mean(eeg_signal)) / (np.std(eeg_signal) + 1e-8)
df_merged['eegRawValueVolts'] = eeg_signal
# 7. Windowing
X_windows = []
window_timestamps = []
total_samples = len(df_merged)
for start in range(0, total_samples - window_size + 1, stride):
segment = df_merged['eegRawValueVolts'].values[start:start + window_size]
X_windows.append(segment.reshape(-1, 1)) # shape (window_size, 1)
window_timestamps.append(df_merged['timestampMs'].values[start]) # start timestamp for window
X_windows = np.array(X_windows)
window_timestamps = np.array(window_timestamps)
return X_windows, window_timestamps |