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
| """ 眼动熵指数计算模块
核心算法: 1. 空间熵(Spatial Entropy) 2. 时间熵(Temporal Entropy) 3. 转移熵(Transition Entropy)
依赖:numpy, scipy """
import numpy as np from scipy.stats import entropy from typing import List, Tuple, Dict from collections import Counter
class EyeMovementEntropy: """ 眼动熵指数计算器 输入: gaze_positions: 视线位置序列 [(x, y), ...] fixation_durations: 注视时长序列 [t1, t2, ...] time_window: 分析窗口(秒) 输出: spatial_entropy: 空间熵 temporal_entropy: 时间熵 transition_entropy: 转移熵 composite_score: 综合熵得分 """ AOI_GRID = { 'road_center': (0.4, 0.6, 0.3, 0.7), 'left_mirror': (0.0, 0.2, 0.3, 0.5), 'right_mirror': (0.8, 1.0, 0.3, 0.5), 'dashboard': (0.3, 0.7, 0.0, 0.3), 'top': (0.3, 0.7, 0.7, 1.0), } def __init__(self, time_window: float = 30.0): """ 初始化 Args: time_window: 分析窗口(秒) """ self.time_window = time_window def calculate( self, gaze_positions: np.ndarray, fixation_durations: np.ndarray, timestamps: np.ndarray ) -> Dict[str, float]: """ 计算眼动熵指标 Args: gaze_positions: 视线位置 (N, 2), 归一化到0-1 fixation_durations: 注视时长 (N,), 单位秒 timestamps: 时间戳 (N,), 单位秒 Returns: entropy_dict: 熵指标字典 """ spatial_ent = self._spatial_entropy(gaze_positions) temporal_ent = self._temporal_entropy(fixation_durations) transition_ent = self._transition_entropy(gaze_positions) composite = 0.4 * spatial_ent + 0.3 * temporal_ent + 0.3 * transition_ent return { 'spatial_entropy': spatial_ent, 'temporal_entropy': temporal_ent, 'transition_entropy': transition_ent, 'composite_score': composite } def _spatial_entropy(self, positions: np.ndarray, grid_size: int = 8) -> float: """ 计算空间熵 方法:将视野划分为grid_size×grid_size网格, 计算视线落入各网格的概率分布,然后计算熵 """ grid_x = np.floor(positions[:, 0] * grid_size).astype(int) grid_y = np.floor(positions[:, 1] * grid_size).astype(int) grid_x = np.clip(grid_x, 0, grid_size - 1) grid_y = np.clip(grid_y, 0, grid_size - 1) grid_indices = grid_x * grid_size + grid_y counter = Counter(grid_indices) total = len(grid_indices) probabilities = np.array([counter[i] / total for i in range(grid_size ** 2)]) probabilities = probabilities[probabilities > 0] spatial_ent = entropy(probabilities, base=2) max_entropy = np.log2(grid_size ** 2) normalized = spatial_ent / max_entropy return normalized def _temporal_entropy(self, durations: np.ndarray, bins: int = 10) -> float: """ 计算时间熵 方法:将注视时长划分为bins个区间, 计算各区间频率分布的熵 """ hist, _ = np.histogram(durations, bins=bins) probabilities = hist / hist.sum() probabilities = probabilities[probabilities > 0] temporal_ent = entropy(probabilities, base=2) max_entropy = np.log2(bins) normalized = temporal_ent / max_entropy return normalized def _transition_entropy(self, positions: np.ndarray) -> float: """ 计算转移熵 方法:统计视线在AOI之间的转移模式, 计算转移序列的熵 """ aoi_sequence = self._assign_aoi(positions) transitions = [] for i in range(len(aoi_sequence) - 1): transition = (aoi_sequence[i], aoi_sequence[i + 1]) transitions.append(transition) if len(transitions) == 0: return 0.0 counter = Counter(transitions) total = len(transitions) probabilities = np.array([count / total for count in counter.values()]) transition_ent = entropy(probabilities, base=2) max_entropy = np.log2(len(counter)) if max_entropy > 0: normalized = transition_ent / max_entropy else: normalized = 0.0 return normalized def _assign_aoi(self, positions: np.ndarray) -> List[str]: """ 分配AOI标签 Args: positions: 视线位置 (N, 2) Returns: aoi_labels: AOI标签列表 """ aoi_labels = [] for x, y in positions: assigned = 'other' for aoi_name, (x1, x2, y1, y2) in self.AOI_GRID.items(): if x1 <= x <= x2 and y1 <= y <= y2: assigned = aoi_name break aoi_labels.append(assigned) return aoi_labels
class CognitiveDistractionDetector: """ 认知分心检测器 方法: 1. 实时计算眼动熵 2. 动态基线对比 3. 阈值判定 """ THRESHOLDS = { 'spatial_entropy_high': 0.6, 'composite_high': 0.55, 'window_sec': 30.0 } def __init__(self): self.entropy_calculator = EyeMovementEntropy() self.baseline = None def update_baseline(self, positions: np.ndarray, durations: np.ndarray, timestamps: np.ndarray): """ 更新基线(正常驾驶时) """ entropy_dict = self.entropy_calculator.calculate(positions, durations, timestamps) self.baseline = entropy_dict def detect(self, positions: np.ndarray, durations: np.ndarray, timestamps: np.ndarray) -> Dict: """ 检测认知分心 Returns: result: { 'is_distracted': bool, 'entropy_scores': dict, 'deviation': float } """ current = self.entropy_calculator.calculate(positions, durations, timestamps) if self.baseline is not None: deviation = current['composite_score'] - self.baseline['composite_score'] else: deviation = 0.0 is_distracted = current['composite_score'] > self.THRESHOLDS['composite_high'] return { 'is_distracted': is_distracted, 'entropy_scores': current, 'deviation': deviation }
if __name__ == "__main__": np.random.seed(42) normal_positions = np.random.normal(0.5, 0.1, (100, 2)) normal_durations = np.random.normal(0.3, 0.05, 100) normal_timestamps = np.arange(100) * 0.1 distracted_positions = np.random.uniform(0, 1, (100, 2)) distracted_durations = np.random.uniform(0.1, 0.8, 100) distracted_timestamps = np.arange(100) * 0.1 detector = CognitiveDistractionDetector() detector.update_baseline(normal_positions, normal_durations, normal_timestamps) normal_result = detector.detect(normal_positions, normal_durations, normal_timestamps) print(f"正常驾驶 - 综合熵: {normal_result['entropy_scores']['composite_score']:.3f}, " f"是否分心: {normal_result['is_distracted']}") distracted_result = detector.detect(distracted_positions, distracted_durations, distracted_timestamps) print(f"认知分心 - 综合熵: {distracted_result['entropy_scores']['composite_score']:.3f}, " f"是否分心: {distracted_result['is_distracted']}, " f"偏差: {distracted_result['deviation']:.3f}")
|