File size: 9,370 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 | #!/usr/bin/env python3
"""Validate one PDM-Lite closed-loop acceptance artifact."""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
FATAL_LOG_PATTERNS = {
"setup_error": re.compile(
r"Skipping scenario|Failed to spawn|Error during the simulation|"
r"Actor .* could not be spawned",
re.IGNORECASE,
),
"carla_crash": re.compile(
r"Signal 11|Segmentation fault|CARLA crash detected|core dumped",
re.IGNORECASE,
),
"scenario_exception": re.compile(
r"Traceback \\(most recent call last\\)|Exception in thread",
re.IGNORECASE,
),
}
EXPECTED_EVENTS = (
"scenario_initialized",
"hint_gate_reached",
"event_triggered",
"hazard_started",
"hazard_cleared",
)
PHYSICAL_COMPLETION_EVENTS = {
"ClosedOccludedPedestrian": "pedestrian_crossing_completed",
"ClosedLaneCutIn": "cut_in_completed",
"ClosedRevealObstacle": "obstacle_reveal_completed",
"ClosedGhostDriverLeftTurn": "hazard_actor_cleared_route",
"ClosedGhostDriverRightTurn": "hazard_actor_cleared_route",
"ClosedSignalizedJunctionRightTurnOnRed": "flow_actor_cleared",
}
PHYSICAL_FAILURE_EVENTS = {
"hazard_crossing_timeout": "pedestrian crossing exceeded its physical completion deadline",
"cut_in_incomplete": "cut-in actor did not enter the ego route",
"obstacle_spawn_failed": "stationary reveal obstacle was not spawned",
"hazard_actor_timeout": "wrong-way actor did not clear the ego route",
"flow_actor_timeout": "yielding flow actor did not clear the conflict area",
}
def _read_jsonl(path: Path) -> list[dict]:
if not path.is_file():
return []
rows = []
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
continue
return rows
def _metric_record(payload: dict) -> dict | None:
records = payload.get("_checkpoint", {}).get("records", [])
return records[-1] if records else None
def validate(run_dir: Path) -> dict:
result_path = run_dir / "results.json"
console_path = run_dir / "logs/acceptance_console.log"
timeline_path = run_dir / "event_timeline.jsonl"
agent_event_path = run_dir / "logs/scenario_events.jsonl"
errors = []
result = {}
record = None
if result_path.is_file():
try:
result = json.loads(result_path.read_text(encoding="utf-8"))
record = _metric_record(result)
except json.JSONDecodeError as exc:
errors.append(f"invalid results.json: {exc}")
else:
errors.append("missing results.json")
if record is None:
errors.append("missing evaluator route record")
status = "Missing"
route_completion = 0.0
infractions = {}
duration_game = 0.0
else:
status = record.get("status", "Unknown")
route_completion = float(record.get("scores", {}).get("score_route", 0.0))
infractions = record.get("infractions", {})
duration_game = float(record.get("meta", {}).get("duration_game", 0.0))
if status not in {"Completed", "Perfect"}:
errors.append(f"route status is {status}")
if route_completion < 99.0:
errors.append(f"route completion is only {route_completion:.2f}")
timeline = _read_jsonl(timeline_path)
event_names = [row.get("event") for row in timeline]
for event_name, message in PHYSICAL_FAILURE_EVENTS.items():
if event_name in event_names:
errors.append(message)
scenario_name = next(
(
str(row.get("scenario_name", ""))
for row in timeline
if row.get("scenario_name")
),
"",
)
scenario_type = next(
(
prefix
for prefix in PHYSICAL_COMPLETION_EVENTS
if scenario_name.startswith(prefix)
),
None,
)
physical_completion_event = (
PHYSICAL_COMPLETION_EVENTS.get(scenario_type)
if scenario_type is not None
else None
)
if physical_completion_event is None:
errors.append(f"unknown scenario lifecycle: {scenario_name or 'missing'}")
else:
completion_count = event_names.count(physical_completion_event)
if completion_count != 1:
errors.append(
f"physical completion event {physical_completion_event} "
f"occurs {completion_count} times"
)
event_index = {}
for name in EXPECTED_EVENTS:
count = event_names.count(name)
if count == 0:
errors.append(f"missing lifecycle event: {name}")
continue
if count != 1:
errors.append(f"lifecycle event {name} occurs {count} times")
event_index[name] = event_names.index(name)
if len(event_index) == len(EXPECTED_EVENTS):
indices = [event_index[name] for name in EXPECTED_EVENTS]
if indices != sorted(indices):
errors.append(f"lifecycle order is invalid: {event_names}")
agent_events = _read_jsonl(agent_event_path)
agent_event_names = [
row.get("event")
for row in agent_events
if row.get("scenario_family") == "COOPERATIVE_AGENT"
]
for name in ("hint_on", "hint_off"):
count = agent_event_names.count(name)
if count != 1:
errors.append(f"cooperative agent event {name} occurs {count} times")
if (
"hint_on" in agent_event_names
and "hint_off" in agent_event_names
and agent_event_names.index("hint_on") > agent_event_names.index("hint_off")
):
errors.append(f"cooperative agent event order is invalid: {agent_event_names}")
event_row = next(
(row for row in timeline if row.get("event") == "event_triggered"),
{},
)
release_reason = event_row.get("release_reason")
elapsed_since_hint = event_row.get("elapsed_since_hint_s")
if release_reason not in {"distance", "timeout"}:
errors.append(f"invalid event release reason: {release_reason}")
if release_reason == "timeout" and elapsed_since_hint is not None:
if not 1.85 <= float(elapsed_since_hint) <= 2.35:
errors.append(
f"anti-deadlock timeout is {float(elapsed_since_hint):.2f} s"
)
frame_files = []
for extension in ("jpg", "jpeg", "png"):
frame_files.extend(run_dir.glob(f"data/**/rgb/*.{extension}"))
frame_count = len(frame_files)
if frame_count < 20:
errors.append(f"only {frame_count} RGB frames")
videos = sorted((run_dir / "videos").glob("*.mp4"))
if not videos:
errors.append("no MP4 video")
console = (
console_path.read_text(encoding="utf-8", errors="replace")
if console_path.is_file()
else ""
)
log_failures = []
for label, pattern in FATAL_LOG_PATTERNS.items():
if pattern.search(console):
log_failures.append(label)
errors.append(f"log contains {label}")
collision_counts = {
key: len(value) if isinstance(value, list) else float(value or 0.0)
for key, value in infractions.items()
if key.startswith("collisions_")
}
collision_total = sum(collision_counts.values())
blocked = infractions.get("vehicle_blocked", [])
blocked_count = len(blocked) if isinstance(blocked, list) else float(blocked or 0.0)
scenario_timeouts = infractions.get("scenario_timeouts", [])
scenario_timeout_count = (
len(scenario_timeouts)
if isinstance(scenario_timeouts, list)
else float(scenario_timeouts or 0.0)
)
if blocked_count:
errors.append(f"vehicle blocked infractions: {blocked_count}")
if collision_total:
errors.append(f"collision infractions: {collision_total}")
if scenario_timeout_count:
errors.append(f"scenario timeout infractions: {scenario_timeout_count}")
return {
"run_dir": str(run_dir),
"accepted": not errors,
"errors": errors,
"route_status": status,
"route_completion": route_completion,
"duration_game_s": duration_game,
"frame_count": frame_count,
"video_count": len(videos),
"lifecycle_events": event_names,
"scenario_name": scenario_name,
"physical_completion_event": physical_completion_event,
"cooperative_agent_events": agent_event_names,
"event_release_reason": release_reason,
"elapsed_since_hint_s": elapsed_since_hint,
"collision_counts": collision_counts,
"blocked_count": blocked_count,
"scenario_timeout_count": scenario_timeout_count,
"log_failures": log_failures,
}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("run_dir", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
report = validate(args.run_dir.resolve())
output = args.output or args.run_dir / "acceptance_report.json"
output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
print(json.dumps(report, indent=2, sort_keys=True))
return 0 if report["accepted"] else 1
if __name__ == "__main__":
raise SystemExit(main())
|