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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
| import numpy as np
class SteeringEntropyCalculator: """ 方向盘操控熵计算 三种熵方法: 1. 传统熵(Shannon Entropy) 2. 近似熵(Approximate Entropy) 3. 样本熵(Sample Entropy) 参考:Towards recognizing cognitive distraction levels (ScienceDirect, 2025) """ def __init__(self): self.threshold = 0.2 def compute_all_entropies(self, steering_sequence, fs=30): """ 计算所有熵类型 Args: steering_sequence: (N,) 方向盘角度序列(度) fs: 采样率(Hz) Returns: entropies: dict """ steering_detrend = self.detrend(steering_sequence) steering_velocity = np.diff(steering_sequence) * fs traditional_entropy = self.traditional_entropy(steering_velocity) approximate_entropy = self.approximate_entropy(steering_velocity, m=2, r=0.2) sample_entropy = self.sample_entropy(steering_velocity, m=2, r=0.2) return { 'traditional_entropy': traditional_entropy, 'approximate_entropy': approximate_entropy, 'sample_entropy': sample_entropy } def detrend(self, sequence): """ 去除趋势 保留高频成分(微修正) """ x = np.arange(len(sequence)) coeffs = np.polyfit(x, sequence, 1) trend = np.polyval(coeffs, x) detrended = sequence - trend return detrended def traditional_entropy(self, sequence, num_bins=10): """ 传统Shannon熵 步骤: 1. 直方图量化 2. 计算概率分布 3. Shannon熵公式 公式:H = -Σ p(x) * log(p(x)) """ hist, _ = np.histogram(sequence, bins=num_bins) prob = hist / len(sequence) entropy = 0 for p in prob: if p > 0: entropy -= p * np.log2(p) max_entropy = np.log2(num_bins) normalized_entropy = entropy / max_entropy return normalized_entropy def approximate_entropy(self, sequence, m=2, r=0.2): """ 近似熵(ApEn) 步骤: 1. 构建m维模式向量 2. 计算相似模式比例 3. 增加维度,重复 参数: - m: 嵌入维度(通常2) - r: 相似度阈值(相对于标准差) 公式:ApEn = Φ_m - Φ_{m+1} """ N = len(sequence) std = np.std(sequence) threshold = r * std phi_m = self._compute_phi(sequence, m, threshold) phi_m1 = self._compute_phi(sequence, m + 1, threshold) apen = phi_m - phi_m1 normalized_apen = min(apen / 2.0, 1.0) return normalized_apen def _compute_phi(self, sequence, m, threshold): """ 计算Φ值 """ N = len(sequence) patterns = [] for i in range(N - m + 1): patterns.append(sequence[i:i+m]) patterns = np.array(patterns) counts = [] for i, p in enumerate(patterns): similar_count = 0 for q in patterns: if np.max(np.abs(p - q)) < threshold: similar_count += 1 counts.append(similar_count / len(patterns)) phi = np.mean(np.log(counts + 1e-10)) return phi def sample_entropy(self, sequence, m=2, r=0.2): """ 样本熵(SampEn) 改进自近似熵: - 避免log(0)问题 - 更好的统计特性 参数: - m: 嵌入维度 - r: 相似度阈值 """ N = len(sequence) std = np.std(sequence) threshold = r * std patterns_m = [] patterns_m1 = [] for i in range(N - m + 1): patterns_m.append(sequence[i:i+m]) for i in range(N - m): patterns_m1.append(sequence[i:i+m+1]) patterns_m = np.array(patterns_m) patterns_m1 = np.array(patterns_m1) def count_similar_pairs(patterns, threshold): count = 0 total_pairs = 0 for i in range(len(patterns)): for j in range(i + 1, len(patterns)): total_pairs += 1 if np.max(np.abs(patterns[i] - patterns[j])) < threshold: count += 1 return count, total_pairs count_m, total_m = count_similar_pairs(patterns_m, threshold) count_m1, total_m1 = count_similar_pairs(patterns_m1, threshold) if total_m > 0 and total_m1 > 0: B = count_m / total_m A = count_m1 / total_m1 if A > 0 and B > 0: sampen = -np.log(A / B) else: sampen = 0 else: sampen = 0 normalized_sampen = min(sampen / 2.0, 1.0) return normalized_sampen
class CognitiveDistractionDetector: """ 基于操控熵的认知分心检测 优势: - 低成本:仅需方向盘角度传感器 - 高灵敏度:样本熵 > 近似熵 > 传统熵 - 实时性:<50ms计算时间 Euro NCAP D-04应用 """ def __init__(self): self.entropy_calculator = SteeringEntropyCalculator() self.history = [] self.window_size = 60 self.fs = 30 def detect(self, steering_sequence): """ 检测认知分心 Args: steering_sequence: (N,) 方向盘角度序列 Returns: result: dict - 'is_cognitive_distraction': bool - 'distraction_level': int (0-3) - 'entropy_values': dict - 'confidence': float """ entropies = self.entropy_calculator.compute_all_entropies( steering_sequence, self.fs ) self.history.append(entropies) sample_entropy = entropies['sample_entropy'] if sample_entropy > 0.7: is_distraction = True level = 3 confidence = 0.85 elif sample_entropy > 0.5: is_distraction = True level = 2 confidence = 0.75 elif sample_entropy > 0.3: is_distraction = True level = 1 confidence = 0.65 else: is_distraction = False level = 0 confidence = 0.9 return { 'is_cognitive_distraction': is_distraction, 'distraction_level': level, 'entropy_values': entropies, 'confidence': confidence } def continuous_monitor(self, steering_stream): """ 持续监控 流式处理方向盘数据 """ window_samples = self.window_size * self.fs buffer = [] for sample in steering_stream: buffer.append(sample) if len(buffer) >= window_samples: window_data = np.array(buffer[-window_samples:]) result = self.detect(window_data) if result['is_cognitive_distraction'] and result['distraction_level'] >= 2: self.trigger_warning(result) buffer = buffer[-int(window_samples * 0.5):] def trigger_warning(self, result): """ 触发Euro NCAP警告 """ level = result['distraction_level'] if level == 3: print("⚠️ 二级警告:重度认知分心") print("建议:立即集中注意力") elif level == 2: print("⚠️ 一级警告:中度认知分心") print("建议:注意驾驶")
def compare_entropies(): """ 对比三种熵的检测性能 """ detector = CognitiveDistractionDetector() scenarios = { 'normal': simulate_normal_driving(duration=120), 'light_distraction': simulate_light_cognitive_distraction(duration=120), 'moderate_distraction': simulate_moderate_cognitive_distraction(duration=120), 'heavy_distraction': simulate_heavy_cognitive_distraction(duration=120) } print("\n" + "="*60) print("三种熵方法对比") print("="*60) for scenario_name, steering_data in scenarios.items(): result = detector.detect(steering_data) print(f"\n场景:{scenario_name}") print(f"传统熵: {result['entropy_values']['traditional_entropy']:.3f}") print(f"近似熵: {result['entropy_values']['approximate_entropy']:.3f}") print(f"样本熵: {result['entropy_values']['sample_entropy']:.3f}") print(f"判定: {'分心' if result['is_cognitive_distraction'] else '正常'}") print(f"分心等级: {result['distraction_level']}") print("="*60)
def test_euro_ncap_d04_entropy(): """ Euro NCAP D-04认知分心测试(操控熵方案) """ detector = CognitiveDistractionDetector() steering_sim = simulate_cognitive_distraction_steering(duration=60) start_time = time.time() result = detector.detect(steering_sim) detection_time = (time.time() - start_time) * 1000 print("\n" + "="*60) print("Euro NCAP D-04认知分心检测(操控熵方案)") print("="*60) print(f"\n是否认知分心: {result['is_cognitive_distraction']}") print(f"分心等级: {result['distraction_level']}") print(f"置信度: {result['confidence']:.2f}") print(f"\n熵值:") print(f"传统熵: {result['entropy_values']['traditional_entropy']:.3f}") print(f"近似熵: {result['entropy_values']['approx_entropy']:.3f}") print(f"样本熵: {result['entropy_values']['sample_entropy']:.3f}") print(f"\n计算时间: {detection_time:.1f}ms") if result['is_cognitive_distraction'] and result['distraction_level'] >= 2: print("\n⚠️ Euro NCAP D-04触发:认知分心检测") print("="*60)
if __name__ == "__main__": compare_entropies() test_euro_ncap_d04_entropy()
|