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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
| 模块清单: 1. Pacejka Magic Formula 轮胎模型 2. Classical Washout 运动提示算法 3. TTC / THW 实时安全指标计算 4. 危险感知 (Hazard Perception) 评分模型 5. 驾驶行为综合安全评分模型 6. 自适应训练难度调节 (RL-based) 7. PERCLOS 疲劳检测模型 8. 驾驶风格分类器 (LSTM-based)
import math import numpy as np from dataclasses import dataclass, field from enum import IntEnum from typing import Optional
@dataclass class PacejkaParams: """Pacejka Magic Formula 参数集""" Bx: float = 10.0 Cx: float = 1.65 Dx: float = 1.0 Ex: float = 0.97 By: float = 8.0 Cy: float = 1.3 Dy: float = 1.0 Ey: float = 0.97 px: float = 0.5 py: float = 0.5
def pacejka_longitudinal(slip_ratio: float, Fz: float, p: PacejkaParams = PacejkaParams()) -> float: """ 计算纵向轮胎力 :param slip_ratio: 滑移率 κ = (ω·R - V) / V, 制动时为负, 驱动时为正 :param Fz: 法向力 (N) :param p: Pacejka参数 :return: 纵向力 Fx (N) """ B, C, D, E = p.Bx, p.Cx, p.Dx, p.Ex kappa = slip_ratio * 100 Fx = Fz * D * math.sin(C * math.atan(B * kappa - E * (B * kappa - math.atan(B * kappa)))) return Fx
def pacejka_lateral(slip_angle: float, Fz: float, p: PacejkaParams = PacejkaParams()) -> float: """ 计算侧向轮胎力 :param slip_angle: 侧偏角 α (rad) :param Fz: 法向力 (N) :param p: Pacejka参数 :return: 侧向力 Fy (N) """ B, C, D, E = p.By, p.Cy, p.Dy, p.Ey alpha = slip_angle * 180 / math.pi Fy = Fz * D * math.sin(C * math.atan(B * alpha - E * (B * alpha - math.atan(B * alpha)))) return Fy
def combined_slip(slip_ratio: float, slip_angle: float, Fz: float, p: PacejkaParams = PacejkaParams()) -> tuple: """ 组合滑移工况下的轮胎力计算 (纵向+侧向耦合) 使用摩擦椭圆修正 :return: (Fx, Fy) 纵向力和侧向力 """ Fx0 = pacejka_longitudinal(slip_ratio, Fz, p) Fy0 = pacejka_lateral(slip_angle, Fz, p)
Fmax = Fz * p.Dx ratio_x = Fx0 / Fmax if Fmax > 0 else 0 ratio_y = Fy0 / Fmax if Fmax > 0 else 0
scale = 1.0 norm = ratio_x**2 + ratio_y**2 if norm > 1.0: scale = 1.0 / math.sqrt(norm)
Fx = Fx0 * scale Fy = Fy0 * scale return Fx, Fy
class ClassicalWashout: """ 经典冲洗运动提示算法
原理: - 高通通道: 提取高频平移加速度 (瞬时加速度), 经冲洗滤波回到中立位 - 低通通道: 提取低频持续加速度, 通过倾斜平台利用重力分量模拟 - 旋转通道: 提取高频角速度/角加速度, 经冲洗滤波
输出: 6-DOF 运动平台指令 (x, y, z, roll, pitch, yaw) """
def __init__(self, dt: float = 0.01): self.dt = dt
self.hp_omega = 2.0 * math.pi * 1.0 self.hp_zeta = 0.7
self.lp_omega = 2.0 * math.pi * 0.5 self.lp_zeta = 1.0
self.hp_rot_omega = 2.0 * math.pi * 2.0 self.hp_rot_zeta = 0.7
self._init_filters()
self.pos = np.zeros(3) self.rot = np.zeros(3) self.vel = np.zeros(3) self.rot_vel = np.zeros(3)
self.max_pos = np.array([0.3, 0.3, 0.15]) self.max_rot = np.array([0.44, 0.44, 0.44])
def _init_filters(self): """初始化离散滤波器状态""" dt = self.dt
wh = self.hp_omega zh = self.hp_zeta a0 = 4 + 4 * zh * wh * dt + wh**2 * dt**2 a1 = -8 + 2 * wh**2 * dt**2 a2 = 4 - 4 * zh * wh * dt + wh**2 * dt**2 b0 = 4 / a0 b1 = -8 / a0 b2 = 4 / a0 self.hp_a = np.array([1, a1 / a0, a2 / a0]) self.hp_b = np.array([b0, b1, b2]) self.hp_state_pos = np.zeros((3, 2)) self.hp_state_acc = np.zeros((3, 2))
wl = self.lp_omega zl = self.lp_zeta a0l = 4 + 4 * zl * wl * dt + wl**2 * dt**2 a1l = -8 + 2 * wl**2 * dt**2 a2l = 4 - 4 * zl * wl * dt + wl**2 * dt**2 b0l = wl**2 * dt**2 / a0l b1l = 2 * wl**2 * dt**2 / a0l b2l = wl**2 * dt**2 / a0l self.lp_a = np.array([1, a1l / a0l, a2l / a0l]) self.lp_b = np.array([b0l, b1l, b2l]) self.lp_state = np.zeros((2, 2))
wr = self.hp_rot_omega zr = self.hp_rot_zeta a0r = 4 + 4 * zr * wr * dt + wr**2 * dt**2 a1r = -8 + 2 * wr**2 * dt**2 a2r = 4 - 4 * zr * wr * dt + wr**2 * dt**2 self.hp_rot_a = np.array([1, a1r / a0r, a2r / a0r]) self.hp_rot_b = np.array([4 / a0r, -8 / a0r, 4 / a0r]) self.hp_rot_state = np.zeros((3, 2))
def _biquad_filter(self, x: float, state: np.ndarray, a: np.ndarray, b: np.ndarray) -> float: """双二阶滤波器""" y = b[0] * x + state[0] state[0] = b[1] * x - a[1] * y + state[1] state[1] = b[2] * x - a[2] * y return y
def update(self, vehicle_acc: np.ndarray, vehicle_rot_rate: np.ndarray, vehicle_rot_acc: np.ndarray) -> np.ndarray: """ 单步更新运动平台指令
:param vehicle_acc: 车辆线加速度 [ax, ay, az] (m/s²) :param vehicle_rot_rate: 车辆角速度 [wx, wy, wz] (rad/s) :param vehicle_rot_acc: 车辆角加速度 [dwx, dwy, dwz] (rad/s²) :return: 平台指令 [x, y, z, roll, pitch, yaw] (m, rad) """ g = 9.81
hp_pos = np.zeros(3) for i in range(3): acc_filtered = self._biquad_filter( vehicle_acc[i], self.hp_state_acc[i], self.hp_a, self.hp_b) self.vel[i] += acc_filtered * self.dt self.pos[i] += self.vel[i] * self.dt self.pos[i] = np.clip(self.pos[i], -self.max_pos[i], self.max_pos[i])
tilt_angles = np.zeros(2) for i in range(2): sustained_acc = self._biquad_filter( vehicle_acc[i], self.lp_state[i], self.lp_a, self.lp_b) tilt_angles[i] = math.atan2(sustained_acc, g)
for i in range(3): self.rot[i] = self._biquad_filter( vehicle_rot_acc[i], self.hp_rot_state[i], self.hp_rot_a, self.hp_rot_b)
platform_cmd = np.zeros(6) platform_cmd[0:3] = self.pos platform_cmd[3] = tilt_angles[1] platform_cmd[4] = -tilt_angles[0] platform_cmd[5] = self.rot[2]
platform_cmd[3:6] = np.clip(platform_cmd[3:6], -self.max_rot, self.max_rot)
return platform_cmd
class SafetyMetrics: """ 实时安全指标计算器
TTC (Time to Collision): 碰撞时间 = 相对距离 / 相对接近速度 THW (Time Headway): 车头时距 = 车间距 / 自车速度 """
TTC_DANGER = 2.0 TTC_WARNING = 4.0 THW_DANGER = 1.0 THW_WARNING = 2.0
@staticmethod def compute_ttc(ego_pos: float, ego_vel: float, target_pos: float, target_vel: float) -> float: """ 计算碰撞时间 TTC :return: TTC (s), 若不收敛返回 float('inf') """ rel_dist = target_pos - ego_pos rel_vel = ego_vel - target_vel
if rel_vel <= 0.01: return float('inf')
ttc = rel_dist / rel_vel return max(ttc, 0.0)
@staticmethod def compute_thw(ego_pos: float, ego_vel: float, lead_pos: float, vehicle_length: float = 4.5) -> float: """ 计算车头时距 THW :param vehicle_length: 前车长度, 用于计算实际间距 :return: THW (s) """ gap = lead_pos - ego_pos - vehicle_length if ego_vel < 0.01: return float('inf') return max(gap / ego_vel, 0.0)
@staticmethod def lane_departure_warning(lateral_offset: float, lane_width: float = 3.75, vehicle_width: float = 1.8) -> tuple: """ 车道偏离检测 :return: (is_departure, deviation_ratio) 偏离比例 0~1 """ half_lane = lane_width / 2 half_vehicle = vehicle_width / 2 threshold = half_lane - half_vehicle deviation = abs(lateral_offset) is_departure = deviation > threshold ratio = min(deviation / threshold, 1.0) if threshold > 0 else 1.0 return is_departure, ratio
@staticmethod def collision_risk_score(ttc: float, thw: float, lane_deviation: float = 0.0) -> float: """ 综合碰撞风险评分 (0-100, 100为最高风险) """ if ttc == float('inf') or ttc > 10: ttc_risk = 0 else: ttc_risk = max(0, 100 * (1 - ttc / 10))
if thw == float('inf') or thw > 5: thw_risk = 0 else: thw_risk = max(0, 100 * (1 - thw / 5))
ld_risk = min(abs(lane_deviation) * 50, 100)
risk = 0.5 * ttc_risk + 0.3 * thw_risk + 0.2 * ld_risk return min(risk, 100.0)
class HazardPerceptionScorer: """ 危险感知评分模型
评估驾驶员发现和响应潜在危险的能力: - 反应时间 (Reaction Time): 从危险出现到驾驶员操作响应的时间 - 注视分布 (Gaze Distribution): 视线是否覆盖关键危险区域 - 预判准确率 (Prediction Accuracy): 是否提前预判危险 - 操作正确性 (Action Correctness): 采取的操作是否正确 """
def __init__(self): self.events: list = [] self.scores: list = []
def record_hazard_event(self, hazard_appear_time: float, driver_response_time: float, gaze_on_hazard: bool, predicted_before_event: bool, action_correct: bool, action_type: str = "brake"): """ 记录一次危险事件并评分
:param hazard_appear_time: 危险出现时间戳 :param driver_response_time: 驾驶员响应时间戳 :param gaze_on_hazard: 驾驶员是否注视了危险区域 :param predicted_before_event: 是否在事件发生前预判到 :param action_correct: 采取的操作是否正确 :param action_type: 操作类型 (brake/steer/brake+steer) """ reaction_time = driver_response_time - hazard_appear_time
if reaction_time <= 0.5: rt_score = 40 elif reaction_time <= 0.8: rt_score = 35 elif reaction_time <= 1.2: rt_score = 28 elif reaction_time <= 1.5: rt_score = 20 elif reaction_time <= 2.0: rt_score = 10 else: rt_score = 0
gaze_score = 20 if gaze_on_hazard else 0
pred_score = 25 if predicted_before_event else 0
action_score = 15 if action_correct else 0
total = rt_score + gaze_score + pred_score + action_score
event_record = { 'reaction_time': reaction_time, 'rt_score': rt_score, 'gaze_score': gaze_score, 'pred_score': pred_score, 'action_score': action_score, 'total_score': total, 'action_type': action_type } self.events.append(event_record) self.scores.append(total)
def get_final_score(self) -> dict: """获取综合危险感知评分""" if not self.scores: return {'hp_score': 0, 'level': '未评估', 'avg_rt': 0}
avg_score = np.mean(self.scores) avg_rt = np.mean([e['reaction_time'] for e in self.events]) gaze_rate = np.mean([e['gaze_score'] > 0 for e in self.events]) pred_rate = np.mean([e['pred_score'] > 0 for e in self.events]) action_rate = np.mean([e['action_score'] > 0 for e in self.events])
if avg_score >= 85: level = "优秀" elif avg_score >= 70: level = "良好" elif avg_score >= 50: level = "合格" elif avg_score >= 30: level = "待提高" else: level = "不合格"
return { 'hp_score': round(avg_score, 1), 'level': level, 'avg_rt': round(avg_rt, 3), 'gaze_rate': round(gaze_rate * 100, 1), 'prediction_rate': round(pred_rate * 100, 1), 'correct_action_rate': round(action_rate * 100, 1), 'total_events': len(self.events) }
class DrivingBehaviorScorer: """ 驾驶行为综合安全评分模型
从多维度评估驾驶安全性: - 速度控制 (Speed Control): 超速、急加速/急减速频率 - 转向稳定性 (Steering Stability): 方向盘操作平顺性、急转向 - 跟车安全 (Following Safety): TTC/THW 违规次数 - 车道保持 (Lane Keeping): 车道偏离次数 - 危险响应 (Hazard Response): 危险事件中的操作正确性 - 规则遵守 (Rule Compliance): 闯红灯、违规变道等 """
WEIGHTS = { 'speed_control': 0.20, 'steering_stability': 0.15, 'following_safety': 0.20, 'lane_keeping': 0.15, 'hazard_response': 0.20, 'rule_compliance': 0.10 }
def __init__(self): self.speed_data: list = [] self.steering_data: list = [] self.acceleration_data: list = [] self.ttc_data: list = [] self.thw_data: list = [] self.lane_deviation_data: list = [] self.hazard_events: list = [] self.violations: list = []
def update_telemetry(self, speed: float, steering_angle: float, acceleration: float, ttc: float, thw: float, lane_deviation: float, timestamp: float): """更新遥测数据""" self.speed_data.append((timestamp, speed)) self.steering_data.append((timestamp, steering_angle)) self.acceleration_data.append((timestamp, acceleration)) self.ttc_data.append((timestamp, ttc)) self.thw_data.append((timestamp, thw)) self.lane_deviation_data.append((timestamp, lane_deviation))
def add_violation(self, violation_type: str, timestamp: float, severity: float): """记录违规事件""" self.violations.append({ 'type': violation_type, 'timestamp': timestamp, 'severity': severity })
def add_hazard_response(self, correct: bool, reaction_time: float): """记录危险响应事件""" self.hazard_events.append({ 'correct': correct, 'reaction_time': reaction_time })
def compute_score(self, speed_limit: float = 60) -> dict: """计算综合安全评分 (0-100)""" scores = {}
if self.speed_data: speeds = [s for _, s in self.speed_data] over_speed_count = sum(1 for s in speeds if s > speed_limit * 1.1) over_speed_ratio = over_speed_count / len(speeds)
hard_acc = sum(1 for a in [a for _, a in self.acceleration_data] if abs(a) > 3.0) hard_acc_ratio = hard_acc / max(len(self.acceleration_data), 1)
speed_score = 100 - over_speed_ratio * 60 - hard_acc_ratio * 40 scores['speed_control'] = max(0, min(100, speed_score)) else: scores['speed_control'] = 100
if len(self.steering_data) > 1: steering = [s for _, s in self.steering_data] steering_rate = np.diff(steering) jerk = np.std(steering_rate) sharp_turns = sum(1 for r in steering_rate if abs(r) > 180) sharp_ratio = sharp_turns / max(len(steering_rate), 1)
steer_score = 100 - min(jerk * 0.3, 50) - sharp_ratio * 50 scores['steering_stability'] = max(0, min(100, steer_score)) else: scores['steering_stability'] = 100
if self.ttc_data: danger_ttc = sum(1 for _, t in self.ttc_data if t < SafetyMetrics.TTC_DANGER) warn_ttc = sum(1 for _, t in self.ttc_data if t < SafetyMetrics.TTC_WARNING) total = len(self.ttc_data) danger_ratio = danger_ttc / total warn_ratio = warn_ttc / total
follow_score = 100 - danger_ratio * 70 - warn_ratio * 30 scores['following_safety'] = max(0, min(100, follow_score)) else: scores['following_safety'] = 100
if self.lane_deviation_data: deviations = [abs(d) for _, d in self.lane_deviation_data] departure_count = sum(1 for d in deviations if d > 1.0) departure_ratio = departure_count / len(deviations) avg_deviation = np.mean(deviations)
lane_score = 100 - departure_ratio * 70 - min(avg_deviation * 30, 30) scores['lane_keeping'] = max(0, min(100, lane_score)) else: scores['lane_keeping'] = 100
if self.hazard_events: correct_rate = sum(1 for e in self.hazard_events if e['correct']) / len(self.hazard_events) avg_rt = np.mean([e['reaction_time'] for e in self.hazard_events]) if avg_rt <= 0.8: rt_factor = 1.0 elif avg_rt <= 1.5: rt_factor = 0.7 elif avg_rt <= 2.0: rt_factor = 0.4 else: rt_factor = 0.1
scores['hazard_response'] = correct_rate * 100 * rt_factor else: scores['hazard_response'] = 100
if self.violations: total_severity = sum(v['severity'] for v in self.violations) violation_penalty = min(total_severity * 25, 100) scores['rule_compliance'] = max(0, 100 - violation_penalty) else: scores['rule_compliance'] = 100
total_score = sum(scores[k] * self.WEIGHTS[k] for k in self.WEIGHTS)
if total_score >= 90: level = "A级 (安全)" elif total_score >= 75: level = "B级 (良好)" elif total_score >= 60: level = "C级 (合格)" elif total_score >= 40: level = "D级 (待提高)" else: level = "E级 (不合格)"
return { 'total_score': round(total_score, 1), 'level': level, 'dimension_scores': {k: round(v, 1) for k, v in scores.items()}, 'violation_count': len(self.violations), 'hazard_event_count': len(self.hazard_events) }
class AdaptiveTrainer: """ 自适应训练难度调节器
根据学员表现动态调整训练场景的难度参数: - 交通密度 (traffic_density): 0.1 ~ 1.0 - 危险事件频率 (hazard_frequency): 0.1 ~ 1.0 - 天气复杂度 (weather_complexity): 0.0 ~ 1.0 - 场景复杂度 (scenario_complexity): 0.1 ~ 1.0
使用基于绩效的动态调整策略: - 表现优秀 → 增加难度 - 表现差 → 降低难度 - 维持在"最近发展区" (Zone of Proximal Development) """
PARAM_RANGES = { 'traffic_density': (0.1, 1.0), 'hazard_frequency': (0.1, 1.0), 'weather_complexity': (0.0, 1.0), 'scenario_complexity': (0.1, 1.0) }
LEARNING_RATE = 0.08 TARGET_SUCCESS_RATE = 0.75
def __init__(self): self.difficulty = { 'traffic_density': 0.3, 'hazard_frequency': 0.2, 'weather_complexity': 0.1, 'scenario_complexity': 0.2 } self.history: list = [] self.weak_areas: dict = {}
def update(self, scenario_score: float, scenario_type: str, performance_details: Optional[dict] = None) -> dict: """ 根据场景表现更新难度
:param scenario_score: 场景得分 0-100 :param scenario_type: 场景类型 :param performance_details: 详细表现数据 :return: 更新后的难度参数 """ self.history.append({ 'score': scenario_score, 'type': scenario_type, 'difficulty': self.difficulty.copy() })
success_rate = scenario_score / 100.0 error = success_rate - self.TARGET_SUCCESS_RATE
adjustment = self.LEARNING_RATE * error
for param in self.difficulty: lo, hi = self.PARAM_RANGES[param] self.difficulty[param] += adjustment * (hi - lo) self.difficulty[param] = np.clip(self.difficulty[param], lo, hi)
if scenario_score < 60: self.weak_areas[scenario_type] = self.weak_areas.get(scenario_type, 0) + 1
return self.difficulty.copy()
def get_training_plan(self) -> dict: """获取训练计划建议""" if self.weak_areas: weakest = max(self.weak_areas, key=self.weak_areas.get) else: weakest = None
recent = self.history[-5:] if len(self.history) >= 5 else self.history if recent: trend = np.mean([h['score'] for h in recent]) else: trend = 0
return { 'current_difficulty': self.difficulty, 'weak_area': weakest, 'recent_avg_score': round(trend, 1), 'total_scenarios': len(self.history), 'recommendation': self._generate_recommendation(trend, weakest) }
def _generate_recommendation(self, trend: float, weak_area: Optional[str]) -> str: """生成训练建议""" if trend < 40: base = "建议降低难度, 重新练习基础场景" elif trend < 60: base = "建议保持当前难度, 巩固薄弱环节" elif trend < 80: base = "表现良好, 可以适度提升难度" else: base = "表现优秀, 建议挑战高难度场景"
if weak_area: base += f"; 重点关注 '{weak_area}' 类型场景的训练"
return base
class PERCLOSDetector: """ PERCLOS (Percentage of Eye Closure) 疲劳检测
原理: 在一定时间窗口内, 眼睑闭合超过80%的时间占比 PERCLOS > 0.15 (15%) → 疲劳预警 PERCLOS > 0.30 (30%) → 严重疲劳告警
结合眨眼频率和注视稳定性进行综合判断 """
WINDOW_SIZE = 60 EYE_CLOSURE_THRESHOLD = 0.8 FATIGUE_WARN = 0.08 FATIGUE_ALERT = 0.15 FATIGUE_SEVERE = 0.30
def __init__(self): self.eye_data: list = [] self.blink_times: list = []
def update(self, eye_closure_ratio: float, timestamp: float): """更新眼动数据""" self.eye_data.append((timestamp, eye_closure_ratio))
if len(self.eye_data) >= 2: prev = self.eye_data[-2][1] if prev < 0.5 and eye_closure_ratio > 0.8: self.blink_times.append(timestamp)
cutoff = timestamp - self.WINDOW_SIZE self.eye_data = [(t, e) for t, e in self.eye_data if t >= cutoff] self.blink_times = [t for t in self.blink_times if t >= cutoff]
def compute_fatigue_level(self) -> dict: """计算疲劳等级""" if len(self.eye_data) < 10: return {'perclos': 0, 'level': '数据不足', 'blink_rate': 0}
closed_count = sum(1 for _, e in self.eye_data if e > self.EYE_CLOSURE_THRESHOLD) perclos = closed_count / len(self.eye_data)
blink_rate = len(self.blink_times) / (self.WINDOW_SIZE / 60)
if len(self.eye_data) > 2: closures = [e for _, e in self.eye_data] gaze_stability = 1.0 - min(np.std(closures) * 2, 1.0) else: gaze_stability = 1.0
if perclos >= self.FATIGUE_SEVERE: level = "严重疲劳" score = 100 elif perclos >= self.FATIGUE_ALERT: level = "疲劳" score = 70 elif perclos >= self.FATIGUE_WARN: level = "轻度疲劳" score = 40 else: level = "清醒" score = 0
if blink_rate < 8 or blink_rate > 30: score = min(score + 15, 100)
return { 'perclos': round(perclos, 4), 'level': level, 'fatigue_score': score, 'blink_rate': round(blink_rate, 1), 'gaze_stability': round(gaze_stability, 3) }
class DrivingStyleClassifier: """ 驾驶风格三分类: 保守型 / 平稳型 / 激进型
基于驾驶操作特征进行分类: - 平均车速 vs 限速比 - 纵向加速度标准差 (加减速激烈程度) - 方向盘角速度标准差 (转向激烈程度) - 矛盾驾驶行为次数 (急加速后急减速等) - 车头时距分布 (跟车距离偏好)
注: 完整实现可使用 LSTM 时序网络, 这里提供基于规则的基线版本 """
def __init__(self): self.features: list = []
def add_features(self, speed: float, speed_limit: float, accel: float, steering_rate: float, thw: float): """添加驾驶特征数据点""" speed_ratio = speed / max(speed_limit, 1) self.features.append({ 'speed_ratio': speed_ratio, 'accel': accel, 'steering_rate': steering_rate, 'thw': thw })
def classify(self) -> dict: """分类驾驶风格""" if len(self.features) < 30: return {'style': '数据不足', 'confidence': 0}
speed_ratios = [f['speed_ratio'] for f in self.features] accels = [f['accel'] for f in self.features] steer_rates = [f['steering_rate'] for f in self.features] thws = [f['thw'] for f in self.features if f['thw'] < float('inf')]
avg_speed_ratio = np.mean(speed_ratios) accel_std = np.std(accels) steer_std = np.std(steer_rates) avg_thw = np.mean(thws) if thws else 3.0 hard_events = sum(1 for a in accels if abs(a) > 2.5)
aggressiveness = 0
if avg_speed_ratio > 0.95: aggressiveness += 30 elif avg_speed_ratio > 0.85: aggressiveness += 20 elif avg_speed_ratio > 0.75: aggressiveness += 10
if accel_std > 2.0: aggressiveness += 30 elif accel_std > 1.2: aggressiveness += 20 elif accel_std > 0.8: aggressiveness += 10
if steer_std > 100: aggressiveness += 20 elif steer_std > 60: aggressiveness += 12 elif steer_std > 30: aggressiveness += 6
if avg_thw < 1.0: aggressiveness += 20 elif avg_thw < 1.5: aggressiveness += 12 elif avg_thw < 2.0: aggressiveness += 6
if aggressiveness >= 65: style = "激进型 (Aggressive)" confidence = min((aggressiveness - 65) / 35 + 0.6, 1.0) elif aggressiveness >= 35: style = "平稳型 (Moderate)" confidence = 1.0 - abs(aggressiveness - 50) / 50 else: style = "保守型 (Conservative)" confidence = min((35 - aggressiveness) / 35 + 0.6, 1.0)
return { 'style': style, 'aggressiveness': round(aggressiveness, 1), 'confidence': round(confidence, 3), 'avg_speed_ratio': round(avg_speed_ratio, 3), 'accel_std': round(accel_std, 3), 'steer_std': round(steer_std, 2), 'avg_thw': round(avg_thw, 2), 'hard_events': hard_events, 'data_points': len(self.features) }
def demo_all(): """运行所有算法的演示"""
print("=" * 70) print(" 防御性安全驾驶模拟器 — 核心算法演示") print("=" * 70)
print("\n[1] Pacejka Magic Formula 轮胎模型") print("-" * 50) Fz = 4000 print(f" 法向力 Fz = {Fz} N") for kappa in [-0.3, -0.2, -0.1, -0.05, 0, 0.05, 0.1, 0.2, 0.3]: Fx = pacejka_longitudinal(kappa, Fz) bar = "█" * int(abs(Fx) / Fz * 40) print(f" κ={kappa:+.2f} Fx={Fx:+8.1f} N ({Fx/Fz:+.3f} μ) {bar}") alpha = 0.1 Fy = pacejka_lateral(alpha, Fz) print(f" 侧偏角 α={math.degrees(alpha):.1f}° Fy={Fy:.1f} N")
print("\n[2] Classical Washout 运动提示算法") print("-" * 50) mca = ClassicalWashout(dt=0.01) print(" 模拟紧急制动 (纵向 -6 m/s², 持续 2s):") for step in range(200): t = step * 0.01 acc = np.array([-6.0, 0, 0]) rot_rate = np.array([0, 0, 0]) rot_acc = np.array([0, 0, 0]) cmd = mca.update(acc, rot_rate, rot_acc) if step % 40 == 0 or step == 199: print(f" t={t:.2f}s 位移=[{cmd[0]:+.3f},{cmd[1]:+.3f},{cmd[2]:+.3f}]m " f"姿态=[{math.degrees(cmd[3]):+.1f},{math.degrees(cmd[4]):+.1f},{math.degrees(cmd[5]):+.1f}]°")
print("\n[3] TTC / THW 安全指标") print("-" * 50) ego_v = 60 / 3.6 lead_v = 40 / 3.6 dist = 30.0 ttc = SafetyMetrics.compute_ttc(0, ego_v, dist, lead_v) thw = SafetyMetrics.compute_thw(0, ego_v, dist) risk = SafetyMetrics.collision_risk_score(ttc, thw) print(f" 场景: 自车 {ego_v:.1f}m/s, 前车 {lead_v:.1f}m/s, 距离 {dist}m") print(f" TTC = {ttc:.2f}s ({'危险!' if ttc < 2 else '警告' if ttc < 4 else '安全'})") print(f" THW = {thw:.2f}s ({'危险!' if thw < 1 else '警告' if thw < 2 else '安全'})") print(f" 碰撞风险评分 = {risk:.1f}/100")
print("\n[4] 危险感知 (Hazard Perception) 评分") print("-" * 50) hp = HazardPerceptionScorer() events = [ (0.0, 0.6, True, True, True), (5.0, 5.9, True, False, True), (10.0, 11.3, True, False, True), (15.0, 15.7, True, True, True), (20.0, 22.2, False, False, False), ] for e in events: hp.record_hazard_event(*e) result = hp.get_final_score() print(f" HP综合评分: {result['hp_score']}/100 ({result['level']})") print(f" 平均反应时间: {result['avg_rt']:.3f}s") print(f" 注视率: {result['gaze_rate']}% 预判率: {result['prediction_rate']}%") print(f" 正确操作率: {result['correct_action_rate']}% 事件数: {result['total_events']}")
print("\n[5] 驾驶行为综合安全评分") print("-" * 50) scorer = DrivingBehaviorScorer() np.random.seed(42) for i in range(200): t = i * 0.1 speed = 55 + np.random.normal(0, 5) steer = np.random.normal(0, 30) accel = np.random.normal(0, 1.5) ttc_val = np.random.uniform(2, 10) thw_val = np.random.uniform(1, 3) lane_dev = np.random.normal(0, 0.3) scorer.update_telemetry(speed, steer, accel, ttc_val, thw_val, lane_dev, t)
scorer.add_violation("超速", 10.0, 0.3) scorer.add_hazard_response(True, 0.8) scorer.add_hazard_response(False, 1.8)
score = scorer.compute_score(speed_limit=60) print(f" 综合评分: {score['total_score']}/100 {score['level']}") print(f" 各维度:") for dim, val in score['dimension_scores'].items(): bar = "█" * int(val / 5) print(f" {dim:25s} {val:5.1f} {bar}") print(f" 违规次数: {score['violation_count']} 危险事件: {score['hazard_event_count']}")
print("\n[6] 自适应训练难度调节") print("-" * 50) trainer = AdaptiveTrainer() scenario_scores = [45, 52, 58, 65, 70, 68, 75, 80, 78, 85] scenario_types = ["路口冲突", "跟车安全", "行人避让", "恶劣天气", "高速场景", "路口冲突", "行人避让", "夜间驾驶", "应急避险", "高速场景"] for i, (s, t) in enumerate(zip(scenario_scores, scenario_types)): diff = trainer.update(s, t) plan = trainer.get_training_plan() print(f" 训练场景数: {plan['total_scenarios']}") print(f" 最近平均分: {plan['recent_avg_score']}") print(f" 薄弱场景: {plan['weak_area'] or '无'}") print(f" 当前难度参数:") for k, v in plan['current_difficulty'].items(): bar = "█" * int(v * 30) print(f" {k:25s} {v:.3f} {bar}") print(f" 建议: {plan['recommendation']}")
print("\n[7] PERCLOS 疲劳检测") print("-" * 50) detector = PERCLOSDetector() np.random.seed(123) for i in range(600): t = i * 0.1 if t < 40: closure = np.random.uniform(0.05, 0.2) if np.random.random() < 0.02: closure = 0.9 else: closure = np.random.uniform(0.3, 0.7) if np.random.random() < 0.08: closure = 0.85 detector.update(closure, t)
fatigue = detector.compute_fatigue_level() print(f" PERCLOS: {fatigue['perclos']:.1%}") print(f" 疲劳等级: {fatigue['level']}") print(f" 疲劳评分: {fatigue['fatigue_score']}/100") print(f" 眨眼频率: {fatigue['blink_rate']:.1f} 次/分钟 (正常 10-20)") print(f" 注视稳定性: {fatigue['gaze_stability']:.3f}")
print("\n[8] 驾驶风格分类") print("-" * 50) classifier = DrivingStyleClassifier() np.random.seed(456) for i in range(100): speed = 62 + np.random.normal(0, 4) accel = np.random.normal(0, 2.5) steer_rate = np.random.normal(0, 80) thw = abs(np.random.normal(1.2, 0.3)) classifier.add_features(speed, 60, accel, steer_rate, thw)
style = classifier.classify() print(f" 驾驶风格: {style['style']}") print(f" 激进度评分: {style['aggressiveness']}/100") print(f" 置信度: {style['confidence']:.1%}") print(f" 平均速度比: {style['avg_speed_ratio']:.2f} (限速比)") print(f" 加速度标准差: {style['accel_std']:.2f} m/s²") print(f" 转向角速度标准差: {style['steer_std']:.1f} °/s") print(f" 平均车头时距: {style['avg_thw']:.2f} s")
print("\n" + "=" * 70) print(" 所有算法演示完成!") print("=" * 70)
if __name__ == "__main__": demo_all()
|