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
| import numpy as np from typing import Dict, List
class AlcoholImpairmentDetector: """ 酒精损伤检测器(多模态融合) 融合: - 方向盘操控熵 - 车道保持性能 - 眼动特征 - 反应时间 """ def __init__(self): self.weights = { 'steering_entropy': 0.30, 'lane_departure': 0.25, 'gaze_features': 0.25, 'reaction_time': 0.20 } self.thresholds = { 'steering_entropy': 0.35, 'lane_departure_rate': 2.5, 'gaze_fixation': 3.0, 'reaction_delay': 0.5 } def compute_steering_entropy(self, steering_angles: np.ndarray) -> float: """ 计算方向盘操控熵(Nakayama方法) Args: steering_angles: 方向盘角度序列(度) Returns: entropy: 操控熵值(0-1) """ predictions = [] for i in range(2, len(steering_angles)): pred = 0.5 * steering_angles[i-1] + 0.5 * steering_angles[i-2] predictions.append(pred) actual = steering_angles[2:] errors = np.abs(actual - predictions) max_error = np.max(errors) + 1e-6 normalized = errors / max_error hist, _ = np.histogram(normalized, bins=20, density=True) hist = hist + 1e-6 entropy = -np.sum(hist * np.log2(hist)) entropy_normalized = entropy / np.log2(20) return entropy_normalized def compute_lane_departure_rate(self, lane_data: List[Dict]) -> float: """ 计算车道偏离频率 Args: lane_data: [{'timestamp': float, 'offset': float, 'event': str}, ...] Returns: rate: 偏离频率(次/分钟) """ departures = [e for e in lane_data if e['event'] == 'departure'] if len(lane_data) > 0: duration = lane_data[-1]['timestamp'] - lane_data[0]['timestamp'] rate = len(departures) / (duration / 60) else: rate = 0 return rate def compute_gaze_features(self, gaze_data: np.ndarray) -> Dict: """ 计算眼动特征 Args: gaze_data: (N, 2) 眼动坐标序列 Returns: features: { 'fixation_duration': float, 'saccade_speed': float, 'off_road_ratio': float } """ diff = np.diff(gaze_data, axis=0) speed = np.sqrt(diff[:, 0]**2 + diff[:, 1]**2) fixation_threshold = 0.05 fixation_frames = speed < fixation_threshold fixation_duration = np.mean(fixation_frames) * 30 saccade_speed = np.mean(speed) * 30 * 100 center = np.array([0.5, 0.5]) distance = np.sqrt((gaze_data[:, 0] - center[0])**2 + (gaze_data[:, 1] - center[1])**2) off_road_ratio = np.mean(distance > 0.3) return { 'fixation_duration': fixation_duration, 'saccade_speed': saccade_speed, 'off_road_ratio': off_road_ratio } def measure_reaction_time(self, stimulus_data: List[Dict]) -> float: """ 测量反应时间 Args: stimulus_data: [{'stimulus': str, 'time': float, 'response': str}, ...] Returns: reaction_time: 平均反应时间(秒) """ reaction_times = [] for i, event in enumerate(stimulus_data): if event['stimulus'] in ['brake_light', 'obstacle']: for j in range(i+1, len(stimulus_data)): if stimulus_data[j].get('response'): rt = stimulus_data[j]['time'] - event['time'] reaction_times.append(rt) break return np.mean(reaction_times) if reaction_times else 0 def detect(self, sensor_data: Dict) -> Dict: """ 多模态融合检测 Args: sensor_data: { 'steering': np.ndarray, 'lane': List[Dict], 'gaze': np.ndarray, 'stimulus': List[Dict] } Returns: { 'impairment_level': 'none' | 'low' | 'high', 'confidence': float, 'modalities': dict } """ steering_entropy = self.compute_steering_entropy(sensor_data['steering']) lane_rate = self.compute_lane_departure_rate(sensor_data['lane']) gaze_features = self.compute_gaze_features(sensor_data['gaze']) reaction_time = self.measure_reaction_time(sensor_data['stimulus']) scores = {} if steering_entropy > self.thresholds['steering_entropy']: scores['steering_entropy'] = min(steering_entropy / self.thresholds['steering_entropy'], 1.0) else: scores['steering_entropy'] = 0 if lane_rate > self.thresholds['lane_departure_rate']: scores['lane_departure'] = min(lane_rate / self.thresholds['lane_departure_rate'], 1.0) else: scores['lane_departure'] = 0 if gaze_features['fixation_duration'] > self.thresholds['gaze_fixation']: scores['gaze_features'] = min(gaze_features['fixation_duration'] / self.thresholds['gaze_fixation'], 1.0) else: scores['gaze_features'] = 0 if reaction_time > self.thresholds['reaction_delay']: scores['reaction_time'] = min(reaction_time / self.thresholds['reaction_delay'], 1.0) else: scores['reaction_time'] = 0 impairment_score = sum(scores[k] * self.weights[k] for k in scores) if impairment_score < 0.3: level = 'none' elif impairment_score < 0.6: level = 'low' else: level = 'high' return { 'impairment_level': level, 'confidence': impairment_score, 'modalities': { 'steering_entropy': steering_entropy, 'lane_departure_rate': lane_rate, 'gaze_features': gaze_features, 'reaction_time': reaction_time, 'scores': scores } }
if __name__ == "__main__": np.random.seed(42) normal_steering = np.cumsum(np.random.randn(300) * 0.5) impaired_steering = np.cumsum(np.random.randn(300) * 2.0) sensor_data_normal = { 'steering': normal_steering, 'lane': [{'timestamp': i/10, 'offset': np.random.randn()*0.1, 'event': 'normal'} for i in range(300)], 'gaze': np.random.rand(300, 2) * 0.2 + 0.4, 'stimulus': [] } sensor_data_impaired = { 'steering': impaired_steering, 'lane': [{'timestamp': i/10, 'offset': np.random.randn()*0.3, 'event': 'departure' if np.random.rand()<0.02 else 'normal'} for i in range(300)], 'gaze': np.random.rand(300, 2) * 0.6 + 0.2, 'stimulus': [] } detector = AlcoholImpairmentDetector() result_normal = detector.detect(sensor_data_normal) result_impaired = detector.detect(sensor_data_impaired) print(f"正常驾驶损伤级别: {result_normal['impairment_level']} (score={result_normal['confidence']:.2f})") print(f"灰色地带损伤级别: {result_impaired['impairment_level']} (score={result_impaired['confidence']:.2f})")
|