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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
| """ 老化驾驶员 EEG 认知控制分析框架 复现论文核心分析流程 """
import numpy as np from scipy.signal import butter, filtfilt, hilbert from dataclasses import dataclass from typing import List, Tuple, Optional
@dataclass class EEGChannel: """EEG 通道定义""" name: str position: tuple region: str
CHANNELS = { 'Fz': EEGChannel('Fz', (0, 0.7), 'frontal'), 'F3': EEGChannel('F3', (-0.5, 0.5), 'frontal'), 'F4': EEGChannel('F4', (0.5, 0.5), 'frontal'), 'Cz': EEGChannel('Cz', (0, 0), 'central'), 'C3': EEGChannel('C3', (-0.5, 0), 'central'), 'C4': EEGChannel('C4', (0.5, 0), 'central'), 'Pz': EEGChannel('Pz', (0, -0.5), 'parietal'), 'P3': EEGChannel('P3', (-0.5, -0.4), 'parietal'), 'P4': EEGChannel('P4', (0.5, -0.4), 'parietal'), 'Oz': EEGChannel('Oz', (0, -0.8), 'occipital'), }
class EEGProcessor: """ EEG 信号处理 Pipeline 流程: 1. 预处理(带通滤波 0.5-30Hz, 陷波 50Hz) 2. ERP 提取(N1, P3, LFN) 3. 时频分析(theta, alpha, beta) 4. MVPA 年龄解码 """ def __init__(self, sample_rate: int = 500): self.fs = sample_rate def preprocess(self, raw: np.ndarray) -> np.ndarray: """ EEG 预处理 Args: raw: 原始 EEG 数据, shape=(n_channels, n_samples) Returns: filtered: 滤波后数据 """ nyq = self.fs / 2 b, a = butter(4, [0.5/nyq, 30/nyq], btype='band') filtered = filtfilt(b, a, raw, axis=1) b_notch, a_notch = butter(4, [49/nyq, 51/nyq], btype='bandstop') filtered = filtfilt(b_notch, a_notch, filtered, axis=1) return filtered def extract_erp(self, eeg: np.ndarray, trigger_times: List[int], pre_stim_ms: int = 200, post_stim_ms: int = 800) -> dict: """ 提取 ERP 成分 Args: eeg: EEG 数据, shape=(n_channels, n_samples) trigger_times: 刺激触发时间点(样本索引) pre_stim_ms: 刺激前时间窗 post_stim_ms: 刺激后时间窗 Returns: {'N1': array, 'P3': array, 'LFN': array} """ pre_samples = int(pre_stim_ms * self.fs / 1000) post_samples = int(post_stim_ms * self.fs / 1000) window_len = pre_samples + post_samples epochs = [] for trigger in trigger_times: start = trigger - pre_samples end = trigger + post_samples if start >= 0 and end < eeg.shape[1]: epoch = eeg[:, start:end] baseline = np.mean(epoch[:, :pre_samples], axis=1, keepdims=True) epoch = epoch - baseline epochs.append(epoch) if not epochs: return {} epochs = np.array(epochs) erp = np.mean(epochs, axis=0) n1_window = (erp[:, int(80*self.fs/1000):int(120*self.fs/1000)]) n1_amplitude = np.min(n1_window, axis=1) p3_window = (erp[:, int(300*self.fs/1000):int(500*self.fs/1000)]) p3_amplitude = np.max(p3_window, axis=1) lfn_window = (erp[:, int(500*self.fs/1000):int(800*self.fs/1000)]) lfn_amplitude = np.mean(lfn_window, axis=1) return { 'N1': n1_amplitude, 'P3': p3_amplitude, 'LFN': lfn_amplitude, 'erp_waveform': erp } def time_frequency_analysis(self, eeg: np.ndarray, trigger_times: List[int], freq_ranges: dict = None) -> dict: """ 时频分析:提取 theta/alpha/beta 能量 Args: eeg: shape=(n_channels, n_samples) trigger_times: 刺激时间点 freq_ranges: 频率范围定义 Returns: {'theta': array, 'alpha': array, 'beta': array} """ if freq_ranges is None: freq_ranges = { 'theta': (4, 8), 'alpha': (8, 13), 'beta': (13, 30) } nyq = self.fs / 2 results = {} for band_name, (f_low, f_high) in freq_ranges.items(): b, a = butter(4, [f_low/nyq, f_high/nyq], btype='band') filtered = filtfilt(b, a, eeg, axis=1) analytic = hilbert(filtered, axis=1) power = np.abs(analytic) ** 2 pre_samples = int(200 * self.fs / 1000) post_samples = int(800 * self.fs / 1000) trials_power = [] for trigger in trigger_times: start = trigger - pre_samples end = trigger + post_samples if start >= 0 and end < power.shape[1]: trials_power.append(power[:, start:end]) if trials_power: results[band_name] = np.mean(trials_power, axis=0) return results def compute_blink_metrics(self, eog_signal: np.ndarray, trigger_times: List[int], window_ms: int = 5000) -> dict: """ 眨眼分析 Args: eog_signal: 眼电信号 (EOG) trigger_times: 刺激时间点 Returns: {'blink_rate': float, 'blink_duration_ms': float, 'amplitude_velocity_ratio': float} """ window_samples = int(window_ms * self.fs / 1000) blink_count = 0 durations = [] amplitudes = [] velocities = [] for trigger in trigger_times: start = trigger end = min(trigger + window_samples, eog_signal.shape[0]) segment = eog_signal[start:end] threshold = 3 * np.std(segment) above = np.abs(segment) > threshold transitions = np.diff(above.astype(int)) starts = np.where(transitions == 1)[0] ends = np.where(transitions == -1)[0] for i in range(min(len(starts), len(ends))): dur_ms = (ends[i] - starts[i]) * 1000 / self.fs amp = np.max(np.abs(segment[starts[i]:ends[i]])) vel = amp / (dur_ms / 1000) if dur_ms > 0 else 0 if dur_ms > 50: blink_count += 1 durations.append(dur_ms) amplitudes.append(amp) velocities.append(vel) blink_rate = blink_count / (window_ms / 60000) return { 'blink_rate': blink_rate, 'blink_duration_ms': np.mean(durations) if durations else 0, 'amplitude_velocity_ratio': np.mean(np.array(amplitudes) / (np.array(velocities) + 1e-10)) if velocities else 0 }
if __name__ == "__main__": processor = EEGProcessor(sample_rate=500) np.random.seed(42) n_channels = 10 n_samples = 5 * 500 raw_eeg = np.random.randn(n_channels, n_samples) * 10 clean_eeg = processor.preprocess(raw_eeg) triggers = [500, 1000, 1500, 2000] erp_results = processor.extract_erp(clean_eeg, triggers) if erp_results: print(f"N1 振幅 (Fz): {erp_results['N1'][0]:.2f} μV") print(f"P3 振幅 (Pz): {erp_results['P3'][6]:.2f} μV") print(f"LFN 振幅 (Fz): {erp_results['LFN'][0]:.2f} μV") tf_results = processor.time_frequency_analysis(clean_eeg, triggers) for band, power in tf_results.items(): print(f"{band} 功率 (平均): {np.mean(power):.2f} μV²") eog = np.random.randn(n_samples) * 20 for t in [500, 1500, 2500]: eog[t:t+100] += 50 * np.exp(-np.linspace(0, 3, 100)) blink_results = processor.compute_blink_metrics(eog, triggers) print(f"\n眨眼率: {blink_results['blink_rate']:.1f} 次/分") print(f"眨眼时长: {blink_results['blink_duration_ms']:.1f} ms") print(f"幅度速度比: {blink_results['amplitude_velocity_ratio']:.2f}")
|