File size: 18,715 Bytes
5a5e5cf | 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 | #!/usr/bin/env python3
"""Single-ego LangCoop adapter for the CoDrive closed-loop benchmark."""
from __future__ import annotations
import json
import math
import os
import sys
import textwrap
import time
import xml.etree.ElementTree as ET
from collections import deque
from pathlib import Path
import carla
import cv2
import numpy as np
import yaml
from leaderboard.autoagents import autonomous_agent
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
LANGCOOP_ROOT = Path(
os.environ.get(
"LANGCOOP_ROOT",
"/path/to/LangCoop",
)
).resolve()
if str(LANGCOOP_ROOT) not in sys.path:
sys.path.insert(0, str(LANGCOOP_ROOT))
from vlmdrive.controller.vlm_controller_speed_curvature import ( # noqa: E402
VLMControllerSpeedCurvature,
)
from vlmdrive.vlm.vlm_planner_speed_curvature import ( # noqa: E402
VLMPlannerSpeedCurvature,
)
def get_entry_point():
return "CoDriveLangCoopAgent"
def _float_attr(element, name, default=0.0):
return float(element.attrib.get(name, default))
class CoDriveLangCoopAgent(autonomous_agent.AutonomousAgent):
"""Run the official LangCoop speed-curvature planner as one CARLA agent.
LangCoop's released evaluator controls multiple ego vehicles and returns a
list of controls. CoDrive uses one ego vehicle, so this adapter preserves
the released planner prompts, parser, and controller while translating the
route navigation target and the temporally bounded cooperative warning.
"""
def setup(self, path_to_conf_file, route_index=None):
del path_to_conf_file, route_index
self.track = autonomous_agent.Track.SENSORS
self.step = -1
self.current_route_hint = None
self._message_disabled = os.environ.get(
"LANGCOOP_DISABLE_MESSAGES",
os.environ.get("SIMLINGO_DISABLE_ROUTE_LEVEL_HINTS", "0"),
).strip().lower() in {"1", "true", "yes", "on"}
self._planning_interval_s = max(
0.25, float(os.environ.get("LANGCOOP_PLANNING_INTERVAL_SECONDS", "2.0"))
)
self._api_base_url = os.environ.get(
"LANGCOOP_API_BASE_URL", "http://127.0.0.1:8032/v1"
)
self._model_name = os.environ.get(
"LANGCOOP_MODEL_NAME", "Qwen/Qwen2.5-VL-3B-Instruct-AWQ"
)
self._run_dir = Path(os.environ["RUN_DIR"]).resolve()
self._save_root = Path(os.environ["SAVE_PATH"]).resolve() / "codrive_langcoop"
self._frame_dir = self._save_root / "rgb_front"
self._frame_dir.mkdir(parents=True, exist_ok=True)
self._log_path = self._run_dir / "langcoop_io.jsonl"
self._log_path.unlink(missing_ok=True)
agent_config = (
LANGCOOP_ROOT
/ "vlmdrive/agent/hypes_yaml/"
"speed_curvature_CoT_concise_image_intent_2agent_qwen.yaml"
)
control_config = (
LANGCOOP_ROOT / "vlmdrive/controller/hypes_yaml/speed_curvature.yaml"
)
self._config = yaml.safe_load(agent_config.read_text(encoding="utf-8"))
control_payload = yaml.safe_load(control_config.read_text(encoding="utf-8"))
self._planner = VLMPlannerSpeedCurvature(
name="api",
api_model_name=self._model_name,
api_base_url=self._api_base_url,
api_key="dummy_key",
)
self._controller = VLMControllerSpeedCurvature(
control_payload["model"]["config"]
)
self._history = deque(maxlen=5)
self._prediction = None
self._prediction_time = None
self._previous_position = None
self._previous_yaw = None
self._route_cursor = 0
self._route_points = []
self._scenario = self._load_scenario_spec(Path(os.environ["ROUTES"]))
self._last_control = carla.VehicleControl()
print(
"[CoDriveLangCoop] "
f"model={self._model_name} api={self._api_base_url} "
f"messages={'off' if self._message_disabled else 'on'} "
f"planning_interval={self._planning_interval_s:.2f}s",
flush=True,
)
@staticmethod
def _load_scenario_spec(route_path):
root = ET.parse(route_path).getroot()
scenario = root.find(".//scenario")
if scenario is None:
return {
"name": "",
"type": "",
"prompt": "",
"collision_point": None,
}
prompt_node = scenario.find("cooperative_prompt")
if prompt_node is None:
prompt_node = scenario.find("./parameters/parameter[@name='cooperative_prompt']")
collision = scenario.find("collision_point")
point = None
if collision is not None:
point = carla.Location(
x=_float_attr(collision, "x"),
y=_float_attr(collision, "y"),
z=_float_attr(collision, "z"),
)
return {
"name": scenario.attrib.get("name", scenario.attrib.get("type", "")),
"type": scenario.attrib.get("type", ""),
"prompt": (
prompt_node.attrib.get("value", "")
if prompt_node is not None
else ""
).strip(),
"collision_point": point,
}
def sensors(self):
return [
{
"type": "sensor.camera.rgb",
"x": 1.3,
"y": 0.0,
"z": 2.3,
"roll": 0.0,
"pitch": 0.0,
"yaw": 0.0,
"width": 800,
"height": 600,
"fov": 100,
"id": "rgb_front",
},
{
"type": "sensor.other.imu",
"x": 0.0,
"y": 0.0,
"z": 0.0,
"roll": 0.0,
"pitch": 0.0,
"yaw": 0.0,
"id": "imu",
},
{
"type": "sensor.other.gnss",
"x": 0.0,
"y": 0.0,
"z": 0.0,
"roll": 0.0,
"pitch": 0.0,
"yaw": 0.0,
"id": "gps",
},
{
"type": "sensor.speedometer",
"reading_frequency": 20,
"id": "speed",
},
]
def _ensure_route_points(self):
if self._route_points:
return
# Leaderboard stores the original dense route before constructing the
# 50 m navigation-command plan. LangCoop needs the dense geometry for
# local steering; using the command plan can place the next target
# across an intersection and cause an immediate off-route turn.
route = (
getattr(self, "org_dense_route_world_coord", None)
or self._global_plan_world_coord
or []
)
for transform, _command in route:
location = transform.location if hasattr(transform, "location") else transform
self._route_points.append(
np.array([float(location.x), float(location.y)], dtype=np.float64)
)
def _navigation_target(self, ego_transform):
self._ensure_route_points()
if not self._route_points:
return np.array([0.0, -20.0], dtype=np.float64)
position = np.array(
[ego_transform.location.x, ego_transform.location.y], dtype=np.float64
)
start = max(0, self._route_cursor - 5)
stop = min(len(self._route_points), self._route_cursor + 80)
nearest = min(
range(start, stop),
key=lambda index: float(np.linalg.norm(self._route_points[index] - position)),
)
self._route_cursor = max(self._route_cursor, nearest)
target_index = nearest
distance = 0.0
while target_index + 1 < len(self._route_points) and distance < 18.0:
distance += float(
np.linalg.norm(
self._route_points[target_index + 1]
- self._route_points[target_index]
)
)
target_index += 1
delta = self._route_points[target_index] - position
yaw = math.radians(float(ego_transform.rotation.yaw))
forward = np.array([math.cos(yaw), math.sin(yaw)])
right = np.array([-math.sin(yaw), math.cos(yaw)])
forward_m = float(delta @ forward)
right_m = float(delta @ right)
# LangCoop describes [lateral, -forward] as right/left and front/back.
return np.array([right_m, -forward_m], dtype=np.float64)
def _event_state(self):
if not self._scenario["name"]:
return {}
try:
from srunner.scenarios.closed_coopeval_scenarios import (
get_ablation_event_state,
)
return get_ablation_event_state(self._scenario["name"]) or {}
except Exception:
return {}
@staticmethod
def _relative_description(ego_transform, point):
if point is None:
return "at the reported conflict point ahead"
delta = np.array(
[
point.x - ego_transform.location.x,
point.y - ego_transform.location.y,
]
)
yaw = math.radians(float(ego_transform.rotation.yaw))
forward = float(delta @ np.array([math.cos(yaw), math.sin(yaw)]))
right = float(delta @ np.array([-math.sin(yaw), math.cos(yaw)]))
lateral = "right" if right >= 0.0 else "left"
longitudinal = "ahead" if forward >= 0.0 else "behind"
return (
f"{abs(forward):.1f} meters {longitudinal} and "
f"{abs(right):.1f} meters to the {lateral}"
)
def _cooperative_message(self, ego_transform):
state = self._event_state()
active = (
not self._message_disabled
and bool(state.get("hint_reached", False))
and not bool(state.get("hazard_cleared", False))
and bool(self._scenario["prompt"])
)
if not active:
self.current_route_hint = None
return ""
position = self._relative_description(
ego_transform, self._scenario["collision_point"]
)
canonical = self._scenario["prompt"]
rendered = canonical.replace("<FRONT_CAR_POS>", position)
self.current_route_hint = {
"name": self._scenario["name"],
"text": canonical,
"rendered_text": rendered,
"position_description": position,
}
return (
"A cooperative road user reports the following safety warning: "
f"{rendered}"
)
@staticmethod
def _speed(input_data):
value = input_data["speed"][1]
if isinstance(value, dict):
if "speed" in value:
return float(value["speed"])
if "move_state" in value:
return float(value["move_state"].get("speed", 0.0))
return float(value)
def _history_record(self, timestamp, speed, ego_transform):
position = np.array(
[ego_transform.location.x, ego_transform.location.y], dtype=np.float64
)
yaw = math.radians(float(ego_transform.rotation.yaw))
if self._previous_position is None:
curvature = 0.0
else:
distance = max(1e-6, float(np.linalg.norm(position - self._previous_position)))
yaw_delta = math.atan2(
math.sin(yaw - self._previous_yaw),
math.cos(yaw - self._previous_yaw),
)
curvature = math.degrees(yaw_delta) / distance
self._previous_position = position
self._previous_yaw = yaw
self._history.append(
{
"timestamp": round(float(timestamp), 3),
"speed": round(float(speed), 3),
"curvature": round(float(curvature), 3),
"waypoints": [0.0, 0.0],
}
)
def _plan(self, image_rgb, timestamp, speed, target, cooperative_message):
prompts = self._config["planning"]["prompt_usage"]
templates = self._config["planning"]["prompt_template"]
scene, scene_prompt = self._planner.get_scene_description(
image_rgb, prompts, templates
)
objects, object_prompt = self._planner.get_objects_description(
image_rgb, prompts, templates
)
target_description = self._planner.get_target_description(target, templates)
intention, intention_prompt = self._planner.get_intent_description(
image_rgb, prompts, target_description, templates
)
history = json.dumps({"ego_history": list(self._history)}, indent=2)
prediction = self._planner._gen_individual_info(
image_rgb,
history,
self._config,
scene,
objects,
intention,
target_description,
cooperative_message,
idx=0,
)
if prediction is None:
raise RuntimeError("LangCoop returned no parseable planning output")
self._prediction = prediction
self._prediction_time = float(timestamp)
record = {
"frame": self.step,
"timestamp": float(timestamp),
"speed_mps": float(speed),
"target_lateral_forward_m": [float(target[0]), float(-target[1])],
"cooperative_message": cooperative_message or None,
"canonical_hint": (
self.current_route_hint["text"] if self.current_route_hint else None
),
"prompts": {
"scene": scene_prompt,
"objects": object_prompt,
"intent": intention_prompt,
},
"intermediate": {
"scene": scene,
"objects": objects,
"intent": intention,
"target": target_description,
},
"prediction": {
"target_speed_mps": [
float(value) for value in prediction["target_speed"]
],
"curvature_degree_per_m": [
float(value) for value in prediction["curvature"]
],
"dt_seconds": float(prediction["dt"]),
},
}
with self._log_path.open("a", encoding="utf-8") as stream:
stream.write(json.dumps(record, ensure_ascii=False) + "\n")
def _fallback_control(self, speed, target):
forward = max(1.0, float(-target[1]))
angle = math.atan2(float(target[0]), forward)
control = carla.VehicleControl()
control.steer = float(np.clip(angle / 0.8, -1.0, 1.0))
control.throttle = 0.45 if speed < 5.0 else 0.15
control.brake = 0.0
return control
def _prediction_control(self, timestamp, speed, target):
if self._prediction is None or self._prediction_time is None:
return self._fallback_control(speed, target)
dt = max(0.1, float(self._prediction["dt"]))
count = len(self._prediction["target_speed"])
index = min(count - 1, max(0, int((float(timestamp) - self._prediction_time) / dt)))
route_info = {
"speed": float(speed),
"target": target,
**self._prediction,
}
steer, throttle, brake, _meta = self._controller.run_step(
route_info, buffer_idx=index
)
return carla.VehicleControl(
steer=float(steer),
throttle=float(throttle),
brake=float(bool(brake)),
hand_brake=False,
)
def _save_frame(self, image_bgr, speed, control, message):
canvas = image_bgr.copy()
lines = [
f"LangCoop | speed={speed:.2f} m/s | "
f"throttle={control.throttle:.2f} brake={control.brake:.0f}",
"Cooperative message: " + (message if message else "None"),
]
y = 28
for line in lines:
for wrapped in textwrap.wrap(line, width=95) or [""]:
cv2.putText(
canvas,
wrapped,
(12, y),
cv2.FONT_HERSHEY_SIMPLEX,
0.52,
(0, 0, 0),
3,
cv2.LINE_AA,
)
cv2.putText(
canvas,
wrapped,
(12, y),
cv2.FONT_HERSHEY_SIMPLEX,
0.52,
(255, 255, 255),
1,
cv2.LINE_AA,
)
y += 22
cv2.imwrite(str(self._frame_dir / f"{self.step:06d}.jpg"), canvas)
def run_step(self, input_data, timestamp):
self.step += 1
raw = input_data["rgb_front"][1]
image_bgr = raw[:, :, :3]
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
speed = self._speed(input_data)
ego = CarlaDataProvider.get_hero_actor()
if ego is None:
return carla.VehicleControl(brake=1.0)
ego_transform = ego.get_transform()
target = self._navigation_target(ego_transform)
message = self._cooperative_message(ego_transform)
self._history_record(timestamp, speed, ego_transform)
should_plan = (
self._prediction is None
or self._prediction_time is None
or float(timestamp) - self._prediction_time >= self._planning_interval_s
)
if should_plan:
started = time.monotonic()
try:
self._plan(image_rgb, timestamp, speed, target, message)
print(
f"[CoDriveLangCoop] planned frame={self.step} "
f"wall_time={time.monotonic() - started:.2f}s "
f"hint={bool(message)}",
flush=True,
)
except Exception as error:
print(f"[CoDriveLangCoop] planning failed: {error}", flush=True)
control = self._prediction_control(timestamp, speed, target)
self._last_control = control
self._save_frame(
image_bgr,
speed,
control,
self.current_route_hint["rendered_text"]
if self.current_route_hint
else "",
)
return control
def destroy(self):
self._planner = None
self._controller = None
|