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
| from enum import Enum from typing import List, Tuple, Optional from dataclasses import dataclass
class RelationOperator(Enum): """Scenic DSL中的空间关系算子""" AHEAD_OF = "ahead of" BEHIND = "behind" LEFT_OF = "left of" RIGHT_OF = "right of" AT = "at"
class FacingOperator(Enum): """朝向关系算子""" AWAY_FROM = "away from" TOWARD = "toward" SAME_DIRECTION = "same direction as" OPPOSITE = "opposite to"
@dataclass class EntityDeclaration: """实体声明""" entity_id: str entity_type: str reference_entity: str relation: RelationOperator facing: FacingOperator distance_range: Tuple[float, float]
@dataclass class SceneProgram: """场景程序""" declarations: List[EntityDeclaration] def to_scenic_code(self) -> str: """生成Scenic代码""" lines = ["ego = new Car on 0@0, facing 0 deg"] for d in self.declarations: line = f"{d.entity_id} = new {d.entity_type} " line += f"{d.relation.value} {d.reference_entity} " line += f"by Range({d.distance_range[0]}, {d.distance_range[1]}), " line += f"facing {d.facing.value} {d.reference_entity}" lines.append(line) return "\n".join(lines)
class StructuralSearch: """ R2SGEN离散结构搜索 搜索空间: 1. 实体声明顺序(O(N!)排列) 2. 参照实体选择(每个实体可引用任意已声明实体) 3. 关系算子选择(ahead/behind/left/right) 通过两种剪枝策略加速: - BFS + Common Prefix Abstraction - DFS + Branch-and-Bound """ def __init__(self, entities: List[dict]): """ Args: entities: 真实场景实体列表 [{'id': 'car1', 'type': 'Car', 'pos': (3,8), 'heading': 0}, ...] """ self.entities = entities self.n = len(entities) self.best_program = None self.best_cost = float('inf') def search_bfs(self) -> Optional[SceneProgram]: """BFS + Common Prefix Abstraction Pruning""" from collections import deque initial_state = ([], set(), 0) queue = deque([initial_state]) while queue: declarations, used, cost = queue.popleft() if cost >= self.best_cost: continue if len(declarations) == self.n: if cost < self.best_cost: self.best_cost = cost self.best_program = SceneProgram(declarations) continue prefix = tuple(d.entity_id for d in declarations) if self._is_dominated_prefix(prefix, cost): continue for entity in self.entities: if entity['id'] in used: continue for ref in [d.entity_id for d in declarations] + ['ego']: for rel in RelationOperator: for face in FacingOperator: new_decl = EntityDeclaration( entity_id=entity['id'], entity_type=entity['type'], reference_entity=ref, relation=rel, facing=face, distance_range=(1, 10) ) if self._verify_smt(new_decl, declarations): new_cost = cost + self._cost(new_decl) new_used = used | {entity['id']} queue.append( (declarations + [new_decl], new_used, new_cost) ) self._record_prefix(prefix, cost) return self.best_program def search_dfs(self) -> Optional[SceneProgram]: """DFS + Branch-and-Bound Pruning""" def dfs_recursive(declarations, used, cost): if cost >= self.best_cost: return if len(declarations) == self.n: if cost < self.best_cost: self.best_cost = cost self.best_program = SceneProgram(declarations) return for entity in self.entities: if entity['id'] in used: continue for ref in [d.entity_id for d in declarations] + ['ego']: for rel in RelationOperator: for face in FacingOperator: new_decl = EntityDeclaration( entity_id=entity['id'], entity_type=entity['type'], reference_entity=ref, relation=rel, facing=face, distance_range=(1, 10) ) if self._verify_smt(new_decl, declarations): new_cost = cost + self._cost(new_decl) dfs_recursive( declarations + [new_decl], used | {entity['id']}, new_cost ) dfs_recursive([], set(), 0) return self.best_program def _verify_smt(self, new_decl, existing) -> bool: """SMT约束验证(简化版)""" entity = next(e for e in self.entities if e['id'] == new_decl.entity_id) ref_entity = next( (e for e in self.entities if e['id'] == new_decl.reference_entity), {'pos': (0, 0), 'heading': 0} ) dx = entity['pos'][0] - ref_entity['pos'][0] dy = entity['pos'][1] - ref_entity['pos'][1] dist = (dx**2 + dy**2) ** 0.5 if not (1 <= dist <= 10): return False if new_decl.relation == RelationOperator.AHEAD_OF: if dy <= 0: return False elif new_decl.relation == RelationOperator.BEHIND: if dy >= 0: return False elif new_decl.relation == RelationOperator.LEFT_OF: if dx >= 0: return False elif new_decl.relation == RelationOperator.RIGHT_OF: if dx <= 0: return False return True def _cost(self, decl: EntityDeclaration) -> float: """程序成本(更简洁=更低成本)""" cost = 0 if decl.relation == RelationOperator.AT: cost += 10 else: cost += 1 if decl.reference_entity == 'ego': cost += 0.5 else: cost += 1.0 return cost def _is_dominated_prefix(self, prefix, cost): """Common Prefix Abstraction 剪枝""" return self._prefix_cache.get(prefix, float('inf')) <= cost def _record_prefix(self, prefix, cost): if not hasattr(self, '_prefix_cache'): self._prefix_cache = {} if prefix not in self._prefix_cache or cost < self._prefix_cache[prefix]: self._prefix_cache[prefix] = cost
if __name__ == "__main__": print("=" * 60) print("R2SGEN 场景程序合成 - 测试") print("=" * 60) entities = [ {'id': 'car1', 'type': 'Car', 'pos': (3, 8), 'heading': 0}, {'id': 'car2', 'type': 'Car', 'pos': (3, 5), 'heading': 0}, {'id': 'car3', 'type': 'Car', 'pos': (0, 5), 'heading': 0}, ] search = StructuralSearch(entities) print("\nBFS搜索...") program = search.search_bfs() if program: print(f"最优成本: {search.best_cost:.2f}") print(f"\n生成的Scenic程序:") print(program.to_scenic_code()) search2 = StructuralSearch(entities) print("\nDFS搜索...") program2 = search2.search_dfs() if program2: print(f"最优成本: {search2.best_cost:.2f}") print(f"\n生成的Scenic程序:") print(program2.to_scenic_code())
|