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
| """ 眼动熵认知分心检测算法 论文:Discriminative Capabilities of Eye Gaze Measures for Cognitive Load Evaluation in a Driving Simulation Task (DOI: 10.3390/jemr19010001)
核心指标:静态眼动熵(SGE)、眼动转移熵(GTE)、注视时长分布 """
import numpy as np from typing import Tuple, List, Dict from collections import Counter from dataclasses import dataclass
@dataclass class GazePoint: """眼动数据点""" timestamp: float x: float y: float pupil_diameter: float = 0.0
class CognitiveDistractionDetector: """认知分心检测器""" def __init__(self, config: dict): """ Args: config: 配置参数 - screen_width: 屏幕宽度(像素) - screen_height: 屏幕高度(像素) - num_zones_x: 水平分区数(默认8) - num_zones_y: 垂直分区数(默认6) - window_duration: 滑动窗口时长(秒,默认30) - min_fixation_duration: 最小注视时长(秒,默认0.1) """ self.screen_width = config.get('screen_width', 1920) self.screen_height = config.get('screen_height', 1080) self.num_zones_x = config.get('num_zones_x', 8) self.num_zones_y = config.get('num_zones_y', 6) self.window_duration = config.get('window_duration', 30.0) self.min_fixation_duration = config.get('min_fixation_duration', 0.1) self.zone_width = self.screen_width / self.num_zones_x self.zone_height = self.screen_height / self.num_zones_y self.sge_threshold_low = 2.5 self.sge_threshold_high = 4.0 self.gte_threshold_low = 1.8 self.fixation_duration_threshold = 0.5 def gaze_to_zone(self, gaze: GazePoint) -> int: """ 将眼动坐标映射到分区索引 Args: gaze: 眼动数据点 Returns: zone_id: 分区索引(0到num_zones_x*num_zones_y-1) """ zone_x = int(gaze.x / self.zone_width) zone_y = int(gaze.y / self.zone_height) zone_x = max(0, min(zone_x, self.num_zones_x - 1)) zone_y = max(0, min(zone_y, self.num_zones_y - 1)) return zone_y * self.num_zones_x + zone_x def calculate_static_gaze_entropy(self, zone_sequence: List[int]) -> float: """ 计算静态眼动熵 (SGE) Args: zone_sequence: 分区索引序列 Returns: SGE: 静态眼动熵(bits) """ if len(zone_sequence) == 0: return 0.0 counter = Counter(zone_sequence) total = len(zone_sequence) entropy = 0.0 for count in counter.values(): if count > 0: p = count / total entropy -= p * np.log2(p) return entropy def calculate_gaze_transition_entropy(self, zone_sequence: List[int]) -> float: """ 计算眼动转移熵 (GTE) Args: zone_sequence: 分区索引序列 Returns: GTE: 眼动转移熵(bits) """ if len(zone_sequence) < 2: return 0.0 num_zones = self.num_zones_x * self.num_zones_y transition_matrix = np.zeros((num_zones, num_zones)) for i in range(len(zone_sequence) - 1): from_zone = zone_sequence[i] to_zone = zone_sequence[i + 1] transition_matrix[from_zone, to_zone] += 1 row_sums = transition_matrix.sum(axis=1, keepdims=True) row_sums[row_sums == 0] = 1 transition_probs = transition_matrix / row_sums zone_probs = transition_matrix.sum(axis=1) / transition_matrix.sum() gte = 0.0 for i in range(num_zones): if zone_probs[i] > 0: for j in range(num_zones): if transition_probs[i, j] > 0: gte -= zone_probs[i] * transition_probs[i, j] * np.log2(transition_probs[i, j]) return gte def detect_fixations(self, gaze_sequence: List[GazePoint]) -> List[Tuple[float, float, float]]: """ 检测注视事件 Args: gaze_sequence: 眼动序列 Returns: fixations: [(start_time, duration, zone_id), ...] """ if len(gaze_sequence) < 2: return [] fixations = [] current_zone = self.gaze_to_zone(gaze_sequence[0]) start_time = gaze_sequence[0].timestamp for i in range(1, len(gaze_sequence)): zone = self.gaze_to_zone(gaze_sequence[i]) if zone != current_zone: duration = gaze_sequence[i].timestamp - start_time if duration >= self.min_fixation_duration: fixations.append((start_time, duration, current_zone)) current_zone = zone start_time = gaze_sequence[i].timestamp duration = gaze_sequence[-1].timestamp - start_time if duration >= self.min_fixation_duration: fixations.append((start_time, duration, current_zone)) return fixations def analyze_temporal_patterns( self, gaze_sequence: List[GazePoint] ) -> Dict[str, float]: """ 分析时序模式特征 Args: gaze_sequence: 眼动序列 Returns: features: { 'sg_entropy': SGE, 'gt_entropy': GTE, 'mean_fixation_duration': 平均注视时长, 'long_fixation_ratio': 长(时间比例, 'scan_path_length': 扫描路径长度, 'saccade_frequency': 眼跳频率 } """ zone_sequence = [self.gaze_to_zone(g) for g in gaze_sequence] sg_entropy = self.calculate_static_gaze_entropy(zone_sequence) gt_entropy = self.calculate_gaze_transition_entropy(zone_sequence) fixations = self.detect_fixations(gaze_sequence) if len(fixations) > 0: fixation_durations = [f[1] for f in fixations] mean_fixation_duration = np.mean(fixation_durations) long_fixation_count = sum(1 for d in fixation_durations if d > self.fixation_duration_threshold) long_fixation_ratio = long_fixation_count / len(fixations) else: mean_fixation_duration = 0.0 long_fixation_ratio = 0.0 scan_path_length = 0.0 for i in range(1, len(gaze_sequence)): dx = gaze_sequence[i].x - gaze_sequence[i-1].x dy = gaze_sequence[i].y - gaze_sequence[i-1].y scan_path_length += np.sqrt(dx**2 + dy**2) total_duration = gaze_sequence[-1].timestamp - gaze_sequence[0].timestamp saccade_frequency = len(fixations) / total_duration if total_duration > 0 else 0.0 return { 'sg_entropy': sg_entropy, 'gt_entropy': gt_entropy, 'mean_fixation_duration': mean_fixation_duration, 'long_fixation_ratio': long_fixation_ratio, 'scan_path_length': scan_path_length, 'saccade_frequency': saccade_frequency } def detect_cognitive_distraction( self, gaze_sequence: List[GazePoint] ) -> Tuple[bool, float, Dict[str, float]]: """ 检测认知分心 Args: gaze_sequence: 眼动序列 Returns: is_distracted: 是否检测到认知分心 confidence: 检测置信度 features: 特征字典 """ features = self.analyze_temporal_patterns(gaze_sequence) score = 0.0 if features['sg_entropy'] < self.sge_threshold_low: score += 0.4 elif features['sg_entropy'] < self.sge_threshold_high: score += 0.2 if features['gt_entropy'] < self.gte_threshold_low: score += 0.3 if features['long_fixation_ratio'] > 0.5: score += 0.2 if features['mean_fixation_duration'] > 0.4: score += 0.1 is_distracted = score > 0.5 confidence = min(score, 1.0) return is_distracted, confidence, features
if __name__ == "__main__": detector = CognitiveDistractionDetector({ 'screen_width': 1920, 'screen_height': 1080, 'num_zones_x': 8, 'num_zones_y': 6, 'window_duration': 30.0 }) np.random.seed(42) num_samples = 900 timestamps = np.linspace(0, 30, num_samples) normal_x = np.random.randn(num_samples) * 200 + 960 normal_y = np.random.randn(num_samples) * 100 + 540 normal_gaze = [ GazePoint(timestamps[i], normal_x[i], normal_y[i]) for i in range(num_samples) ] distracted_x = np.random.randn(num_samples) * 50 + 960 distracted_y = np.random.randn(num_samples) * 30 + 400 distracted_gaze = [ GazePoint(timestamps[i], distracted_x[i], distracted_y[i]) for i in range(num_samples) ] print("=" * 60) print("正常驾驶状态检测:") is_distracted, confidence, features = detector.detect_cognitive_distraction(normal_gaze) print(f"是否分心: {is_distracted}") print(f"置信度: {confidence:.2%}") print(f"特征详情:") for key, value in features.items(): print(f" {key}: {value:.3f}") print("\n" + "=" * 60) print("认知分心状态检测:") is_distracted, confidence, features = detector.detect_cognitive_distraction(distracted_gaze) print(f"是否分心: {is_distracted}") print(f"置信度: {confidence:.2%}") print(f"特征详情:") for key, value in features.items(): print(f" {key}: {value:.3f}") print("\n" + "=" * 60) print("熵值对比分析:") print(f"正常驾驶 SGE: {detector.analyze_temporal_patterns(normal_gaze)['sg_entropy']:.2f} bits") print(f"认知分心 SGE: {detector.analyze_temporal_patterns(distracted_gaze)['sg_entropy']:.2f} bits") print(f"理论最大熵: {np.log2(8 * 6):.2f} bits (8×6分区)")
|