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
| """ CPD 自动化测试管道 基于: Zyberaj et al., arXiv:2608.19752
功能: 1. 部署感知场景生成 2. CPD 算法测试 3. 自动评估与报告
依赖: pip install numpy dataclasses json """
import numpy as np from dataclasses import dataclass, field from typing import List, Dict, Optional from enum import Enum import json import time
class VehicleType(Enum): SEDAN = "sedan" SUV = "suv" VAN = "van"
class SensorType(Enum): UWB = "uwb" RADAR_60GHZ = "60ghz" CAMERA = "camera" MICROPHONE = "microphone"
@dataclass class DeploymentConfig: """部署配置""" vehicle_type: VehicleType = VehicleType.SUV sensors: List[SensorType] = field(default_factory=lambda: [ SensorType.UWB, SensorType.RADAR_60GHZ, SensorType.CAMERA ]) num_seats: int = 5 has_trunk: bool = True climate_zone: str = "temperate" temperature_range: tuple = (-20, 50) humidity_range: tuple = (20, 80)
@dataclass class CPDTestScenario: """CPD 测试场景""" name: str occupant_position: str occupant_type: str obstruction: str environment: str expected_detection: bool response_time_limit: float = 6.0
class CPDTestPipeline: """CPD 自动化测试管道""" def __init__(self, config: DeploymentConfig): self.config = config self.scenarios: List[CPDTestScenario] = [] self.results: List[dict] = [] def generate_scenarios(self) -> List[CPDTestScenario]: """根据部署配置动态生成测试场景""" scenarios = [] positions = ['front_passenger', 'rear_left', 'rear_right'] if self.config.has_trunk: positions.append('trunk') occupants = ['adult', 'child', 'infant'] obstructions = ['none', 'blanket', 'seat', 'clothing'] environments = ['normal', 'dark', 'hot', 'cold'] for pos in positions: for occ in occupants: for obs in obstructions: for env in environments: detectable = self._is_detectable(pos, occ, obs) scenario = CPDTestScenario( name=f"{occ}_{pos}_{obs}_{env}", occupant_position=pos, occupant_type=occ, obstruction=obs, environment=env, expected_detection=detectable ) scenarios.append(scenario) for pos in positions: for env in environments: scenarios.append(CPDTestScenario( name=f"empty_{pos}_{env}", occupant_position=pos, occupant_type='none', obstruction='none', environment=env, expected_detection=False )) self.scenarios = scenarios return scenarios def _is_detectable(self, position: str, occupant: str, obstruction: str) -> bool: """判断场景是否应被检测到""" if occupant == 'none': return False if SensorType.UWB in self.config.sensors: return True if SensorType.RADAR_60GHZ in self.config.sensors: if obstruction in ['blanket', 'seat'] and occupant == 'infant': return False return True if SensorType.CAMERA in self.config.sensors: if obstruction != 'none': return False if position == 'trunk': return False return True return True def run_test(self, scenario: CPDTestScenario) -> dict: """运行单个测试场景""" detection_result = self._simulate_cpd(scenario) correct = detection_result['detected'] == scenario.expected_detection tp = detection_result['detected'] and scenario.expected_detection fp = detection_result['detected'] and not scenario.expected_detection fn = not detection_result['detected'] and scenario.expected_detection tn = not detection_result['detected'] and not scenario.expected_detection return { 'scenario': scenario.name, 'expected': scenario.expected_detection, 'detected': detection_result['detected'], 'response_time': detection_result['response_time'], 'confidence': detection_result['confidence'], 'correct': correct, 'outcome': 'TP' if tp else ('FP' if fp else ('FN' if fn else 'TN')) } def _simulate_cpd(self, scenario: CPDTestScenario) -> dict: """模拟 CPD 算法""" if scenario.occupant_type == 'none': false_positive_rate = 0.02 detected = np.random.random() < false_positive_rate return { 'detected': detected, 'response_time': np.random.exponential(3.0) if detected else 0, 'confidence': np.random.uniform(0.6, 0.8) if detected else 0.1 } base_prob = 0.95 obs_penalty = { 'none': 0.0, 'blanket': 0.05, 'seat': 0.10, 'clothing': 0.03 } env_penalty = { 'normal': 0.0, 'dark': 0.05, 'hot': 0.02, 'cold': 0.03 } occ_bonus = { 'adult': 0.03, 'child': 0.0, 'infant': -0.05 } sensor_bonus = len(self.config.sensors) * 0.01 prob = (base_prob - obs_penalty.get(scenario.obstruction, 0) - env_penalty.get(scenario.environment, 0) + occ_bonus.get(scenario.occupant_type, 0) + sensor_bonus) detected = np.random.random() < prob response_time = np.random.uniform(1.0, 5.5) if detected else 0 return { 'detected': detected, 'response_time': response_time, 'confidence': np.random.uniform(0.85, 0.99) if detected else 0.1 } def run_all_tests(self) -> Dict: """运行所有测试""" self.results = [] for scenario in self.scenarios: result = self.run_test(scenario) self.results.append(result) return self.generate_report() def generate_report(self) -> Dict: """生成测试报告""" total = len(self.results) correct = sum(1 for r in self.results if r['correct']) tp = sum(1 for r in self.results if r['outcome'] == 'TP') fp = sum(1 for r in self.results if r['outcome'] == 'FP') fn = sum(1 for r in self.results if r['outcome'] == 'FN') tn = sum(1 for r in self.results if r['outcome'] == 'TN') precision = tp / (tp + fp) if (tp + fp) > 0 else 0 recall = tp / (tp + fn) if (tp + fn) > 0 else 0 f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 response_times = [r['response_time'] for r in self.results if r['detected']] return { 'total_scenarios': total, 'correct_predictions': correct, 'accuracy': round(correct / total * 100, 1) if total else 0, 'true_positives': tp, 'false_positives': fp, 'false_negatives': fn, 'true_negatives': tn, 'precision': round(precision * 100, 1), 'recall': round(recall * 100, 1), 'f1_score': round(f1 * 100, 1), 'mean_response_time': round(np.mean(response_times), 2) if response_times else 0, 'max_response_time': round(max(response_times), 2) if response_times else 0, 'false_alarm_rate_per_24h': round(fp / total * 24, 2), }
if __name__ == "__main__": print("=" * 70) print("CPD 自动化测试管道") print("基于: Zyberaj et al., arXiv:2608.19752") print("=" * 70) config = DeploymentConfig( vehicle_type=VehicleType.SUV, sensors=[SensorType.UWB, SensorType.RADAR_60GHZ, SensorType.CAMERA], num_seats=5, has_trunk=True, ) print(f"\n部署配置:") print(f" 车型: {config.vehicle_type.value}") print(f" 传感器: {[s.value for s in config.sensors]}") print(f" 座位数: {config.num_seats}") print(f" 有后备箱: {config.has_trunk}") pipeline = CPDTestPipeline(config) scenarios = pipeline.generate_scenarios() print(f"\n生成测试场景: {len(scenarios)} 个") by_type = {} for s in scenarios: by_type[s.occupant_type] = by_type.get(s.occupant_type, 0) + 1 print(f" 乘员类型分布: {by_type}") by_env = {} for s in scenarios: by_env[s.environment] = by_env.get(s.environment, 0) + 1 print(f" 环境条件分布: {by_env}") print(f"\n运行测试...") report = pipeline.run_all_tests() print(f"\n{'='*70}") print("测试报告") print(f"{'='*70}") print(f"\n{'指标':<25s} {'数值':>10s}") print("-" * 40) for key, val in report.items(): if isinstance(val, float): print(f" {key:<23s} {val:>10.2f}") else: print(f" {key:<23s} {val:>10}") print(f"\n{'='*70}") print("不同传感器配置对比") print(f"{'='*70}") configs = [ ("UWB + 60GHz + Camera", [SensorType.UWB, SensorType.RADAR_60GHZ, SensorType.CAMERA]), ("UWB + 60GHz", [SensorType.UWB, SensorType.RADAR_60GHZ]), ("60GHz + Camera", [SensorType.RADAR_60GHZ, SensorType.CAMERA]), ("仅 UWB", [SensorType.UWB]), ("仅 60GHz", [SensorType.RADAR_60GHZ]), ("仅 Camera", [SensorType.CAMERA]), ] print(f"\n{'传感器组合':<25s} {'准确率':>8s} {'精确率':>8s} {'召回率':>8s} {'F1':>6s} {'误报/24h':>10s}") print("-" * 68) for name, sensors in configs: cfg = DeploymentConfig(sensors=sensors) pipe = CPDTestPipeline(cfg) pipe.generate_scenarios() rep = pipe.run_all_tests() print(f"{name:<25s} {rep['accuracy']:>7.1f}% {rep['precision']:>7.1f}% " f"{rep['recall']:>7.1f}% {rep['f1_score']:>5.1f} {rep['false_alarm_rate_per_24h']:>9.2f}")
|