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
| """ 搜索驱动VLM测试框架 论文方法:遗传算法/爬山算法主动发现失效场景 """
import numpy as np import random from typing import List, Tuple, Callable
class SearchBasedTester: """论文核心方法:搜索驱动测试 目标:最大化测试集直径(Test Set Diameter) - 覆盖更多边缘场景 - 发现传统固定测试集遗漏的失效案例 搜索算法: - Genetic Algorithm (GA) - Hill Climbing (HC) """ def __init__(self, vlm_predictor: Callable, target_scenario: str): """ Args: vlm_predictor: VLM预测函数 target_scenario: Euro NCAP场景编号(如D-02) """ self.predictor = vlm_predictor self.scenario = target_scenario self.param_ranges = { "D-02": { "phone_position": ["ear", "face", "chest", "lap"], "hand_gesture": ["hold", "typing", "scrolling"], "duration_sec": (1.0, 10.0), "lighting": ["day", "night", "tunnel"], "occlusion": ["none", "partial", "heavy"], }, "D-05": { "gaze_offset_deg": (0, 45), "direction": ["left", "right", "up", "down"], "duration_sec": (0.5, 10.0), "head_pose": ["normal", "tilted", "turned"], } } def generate_random_test_case(self) -> dict: """随机生成测试参数""" params = {} scenario_params = self.param_ranges[self.scenario] for key, value in scenario_params.items(): if isinstance(value, list): params[key] = random.choice(value) elif isinstance(value, tuple): params[key] = random.uniform(value[0], value[1]) return params def evaluate_test_case(self, test_params: dict) -> Tuple[bool, float]: """ 评估单个测试案例 Args: test_params: 测试参数 Returns: is_failure: 是否为失效案例(VLM预测错误) failure_score: 失效严重程度(0-1) """ pred_result = self.predictor(test_params) if self.scenario == "D-02": ground_truth = test_params["duration_sec"] >= 3.0 is_detected = pred_result["phone_detected"] and pred_result["duration"] >= 3.0 is_failure = not is_detected if ground_truth else False if is_failure: failure_score = test_params["duration_sec"] / 10.0 else: failure_score = 0.0 elif self.scenario == "D-05": ground_truth = test_params["duration_sec"] >= 3.0 is_detected = pred_result["gaze_deviation"] and pred_result["duration"] >= 3.0 is_failure = not is_detected if ground_truth else False failure_score = test_params["gaze_offset_deg"] / 45.0 if is_failure else 0.0 return is_failure, failure_score def genetic_algorithm_search(self, population_size=50, generations=20) -> List[dict]: """ 遗传算法搜索失效场景 论文方法:最大化失效发现率 Args: population_size: 种群大小 generations: 进化代数 Returns: failure_cases: 发现的失效案例列表 """ population = [self.generate_random_test_case() for _ in range(population_size)] failure_cases = [] for gen in range(generations): fitness_scores = [] for test_case in population: is_failure, score = self.evaluate_test_case(test_case) fitness_scores.append(score) if is_failure: failure_cases.append(test_case) total_fitness = sum(fitness_scores) if total_fitness == 0: selected = random.sample(population, population_size // 2) else: probs = [s / total_fitness for s in fitness_scores] selected_indices = np.random.choice( len(population), size=population_size // 2, p=probs ) selected = [population[i] for i in selected_indices] new_population = selected.copy() while len(new_population) < population_size: parent1, parent2 = random.sample(selected, 2) child = self._crossover(parent1, parent2) new_population.append(child) for i in range(len(new_population)): if random.random() < 0.1: new_population[i] = self._mutate(new_population[i]) population = new_population return failure_cases def _crossover(self, parent1: dict, parent2: dict) -> dict: """交叉操作:混合两个父代参数""" child = {} for key in parent1.keys(): if random.random() < 0.5: child[key] = parent1[key] else: child[key] = parent2[key] return child def _mutate(self, test_case: dict) -> dict: """变异操作:随机修改一个参数""" mutated = test_case.copy() key = random.choice(list(mutated.keys())) scenario_params = self.param_ranges[self.scenario] value_range = scenario_params[key] if isinstance(value_range, list): mutated[key] = random.choice(value_range) elif isinstance(value_range, tuple): mutated[key] = random.uniform(value_range[0], value_range[1]) return mutated def calculate_test_set_diameter(self, test_cases: List[dict]) -> float: """ 计算测试集直径(论文核心指标) 论文引用Feldt et al. 2016 ICST: Test Set Diameter = 最大最小距离 - 量化测试多样性 - 覆盖边缘场景能力 Args: test_cases: 测试案例集合 Returns: diameter: 测试集直径 """ vectors = [] for tc in test_cases: vec = [] for key, value in tc.items(): if isinstance(value, str): options = self.param_ranges[self.scenario][key] vec.append(options.index(value) if value in options else 0) else: range_val = self.param_ranges[self.scenario][key] if isinstance(range_val, tuple): normalized = (value - range_val[0]) / (range_val[1] - range_val[0]) vec.append(normalized) vectors.append(np.array(vec)) min_distances = [] for i, v1 in enumerate(vectors): distances = [] for j, v2 in enumerate(vectors): if i != j: dist = np.linalg.norm(v1 - v2) distances.append(dist) if distances: min_distances.append(min(distances)) diameter = max(min_distances) if min_distances else 0 return diameter
def mock_vlm_predictor(test_params: dict) -> dict: """模拟VLM预测结果""" if test_params.get("lighting") == "night" and test_params.get("occlusion") == "partial": return { "phone_detected": False, "gaze_deviation": False, "duration": 0.0 } return { "phone_detected": True, "gaze_deviation": True, "duration": test_params.get("duration_sec", 3.0) }
if __name__ == "__main__": tester = SearchBasedTester(mock_vlm_predictor, "D-02") print("搜索驱动VLM测试演示:") print("-" * 70) failures = tester.genetic_algorithm_search(population_size=30, generations=10) print(f"发现失效案例数: {len(failures)}") if failures: print("\n失效案例分析:") for i, case in enumerate(failures[:5], 1): print(f"#{i}: 光照={case.get('lighting')} 遮挡={case.get('occlusion')} " f"时长={case.get('duration_sec', 0):.1f}s") diameter = tester.calculate_test_set_diameter(failures) print(f"\n测试集直径: {diameter:.3f}") print("直径越大 → 覆盖边缘场景越多")
|