Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
435 lines (353 loc) · 15.5 KB
/
Copy pathbenchmark.py
File metadata and controls
435 lines (353 loc) · 15.5 KB
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
"""Benchmarking system for mobile manipulator planning.
This module provides a unified BenchmarkRecorder that combines:
- State monitoring (via SimulationMonitor)
- Video recording (via VideoRecorder)
- Log capture
- Result serialization
"""
from __future__ import annotations
import csv
import subprocess
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
import numpy as np
# Import modular components
from simulation_monitor import (
SimulationMonitor,
StateRecord,
PlanningRecord,
PhaseRecord,
)
from video_recorder import VideoRecorder
def get_git_commit_id() -> str:
"""Get the current git commit ID (short hash)."""
try:
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
return result.stdout.strip()
except Exception:
pass
return "unknown"
class LogCapture:
"""Context manager to capture stdout/stderr to a file while still printing."""
def __init__(self, log_path: Path):
self.log_path = log_path
self.log_file = None
self._original_stdout = None
self._original_stderr = None
def __enter__(self):
import sys
self.log_file = open(self.log_path, 'w')
self._original_stdout = sys.stdout
self._original_stderr = sys.stderr
sys.stdout = TeeWriter(self._original_stdout, self.log_file)
sys.stderr = TeeWriter(self._original_stderr, self.log_file)
return self
def __exit__(self, *args):
import sys
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
if self.log_file:
self.log_file.close()
class TeeWriter:
"""Writer that writes to multiple outputs."""
def __init__(self, *writers):
self.writers = writers
def write(self, text):
for w in self.writers:
w.write(text)
w.flush()
def flush(self):
for w in self.writers:
w.flush()
@dataclass
class BenchmarkResult:
"""Complete benchmark result for one scenario run."""
scenario_id: str
run_timestamp: str
random_seed: int | None
# Scenario info
layout: list[str] = field(default_factory=list)
goal_positions: list[tuple[float, float, float]] = field(default_factory=list)
# Trajectory data (uses StateRecord from simulation_monitor)
trajectory: list[StateRecord] = field(default_factory=list)
# Planning results (uses PlanningRecord from simulation_monitor)
planning_records: list[PlanningRecord] = field(default_factory=list)
# Phase timing (uses PhaseRecord from simulation_monitor)
phase_records: list[PhaseRecord] = field(default_factory=list)
# Collision events
collision_events: list[tuple[float, np.ndarray]] = field(default_factory=list)
# Final status
task_success: bool = False
reached_goals: list[bool] = field(default_factory=list)
# Computed metrics (filled by finalize())
total_execution_time: float = 0.0
total_planning_time: float = 0.0
total_path_length: float = 0.0
min_obstacle_margin: float = float('inf')
avg_obstacle_margin: float = 0.0
safety_rate: float = 0.0
avg_mpc_latency: float = 0.0
max_mpc_latency: float = 0.0
def to_summary_dict(self) -> dict[str, Any]:
"""Convert to dictionary for CSV export."""
return {
"scenario_id": self.scenario_id,
"timestamp": self.run_timestamp,
"random_seed": self.random_seed,
"task_success": self.task_success,
"collision_count": len(self.collision_events),
"total_execution_time": self.total_execution_time,
"total_planning_time": self.total_planning_time,
"total_path_length": self.total_path_length,
"min_obstacle_margin": self.min_obstacle_margin,
"avg_obstacle_margin": self.avg_obstacle_margin,
"safety_rate": self.safety_rate,
"avg_mpc_latency": self.avg_mpc_latency,
"max_mpc_latency": self.max_mpc_latency,
"num_goals_reached": sum(self.reached_goals),
"num_goals_total": len(self.reached_goals),
}
class BenchmarkRecorder:
"""
Records benchmark data during a single scenario execution.
Combines SimulationMonitor and VideoRecorder into a unified interface
with output management and result serialization.
"""
def __init__(
self,
scenario_id: str | None = None,
random_seed: int | None = None,
output_dir: str = None,
safety_margin: float = None,
):
# Import config for defaults
try:
import config
default_output_dir = config.BENCHMARK_OUTPUT_DIR
default_safety_margin = config.BENCHMARK_SAFETY_MARGIN
except (ImportError, AttributeError):
default_output_dir = "benchmarks"
default_safety_margin = 0.1
self.safety_margin = safety_margin if safety_margin is not None else default_safety_margin
self.random_seed = random_seed
# Get git commit ID and create unique run folder
self.commit_id = get_git_commit_id()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
seed_str = f"seed{random_seed}" if random_seed is not None else "seedNone"
self.run_folder_name = f"{self.commit_id}_{seed_str}_{timestamp}"
self.scenario_id = scenario_id or self.run_folder_name
# Create unique output directory for this run
base_output_dir = Path(output_dir) if output_dir else Path(default_output_dir)
self.output_dir = base_output_dir / self.run_folder_name
# Create output directories
self.output_dir.mkdir(parents=True, exist_ok=True)
(self.output_dir / "results").mkdir(parents=True, exist_ok=True)
(self.output_dir / "plots").mkdir(parents=True, exist_ok=True)
# Initialize modular components
self._monitor = SimulationMonitor(safety_margin=self.safety_margin)
self._video_recorder = VideoRecorder(output_dir=self.output_dir / "videos")
# Initialize result
self.result = BenchmarkResult(
scenario_id=self.scenario_id,
run_timestamp=datetime.now().isoformat(),
random_seed=random_seed,
)
# Log capture
self._log_capture = None
self.log_path = self.output_dir / "terminal_log.txt"
# === Log capture methods ===
def start_log_capture(self) -> None:
"""Start capturing terminal output to log file."""
self._log_capture = LogCapture(self.log_path)
self._log_capture.__enter__()
print(f"=== Benchmark Run: {self.run_folder_name} ===")
print(f"Git commit: {self.commit_id}")
print(f"Seed: {self.random_seed}")
print(f"Output dir: {self.output_dir}")
print("=" * 50)
def stop_log_capture(self) -> None:
"""Stop capturing terminal output."""
if self._log_capture:
self._log_capture.__exit__(None, None, None)
self._log_capture = None
# === Video recording methods (delegate to VideoRecorder) ===
def start_video_recording(self, filename: str = None) -> str | None:
"""Start recording video. Returns path to video file."""
if filename is None:
filename = self.scenario_id
return self._video_recorder.start(filename)
def stop_recording(self) -> None:
"""Stop video recording."""
self._video_recorder.stop()
# === Scenario info methods ===
def set_layout(self, layout: list[str]) -> None:
"""Record the warehouse layout."""
self.result.layout = layout.copy()
def set_goal_positions(self, goals: list[tuple[float, float, float]]) -> None:
"""Record the goal positions."""
self.result.goal_positions = goals.copy()
self.result.reached_goals = [False] * len(goals)
self._monitor.set_goal_positions(goals)
# === Phase timing methods (delegate to SimulationMonitor) ===
def start_phase(self, phase_name: str) -> None:
"""Start timing a phase."""
self._monitor.start_phase(phase_name)
def end_phase(self, phase_name: str, success: bool = True) -> None:
"""End timing a phase."""
self._monitor.end_phase(phase_name, success)
# === State recording methods (delegate to SimulationMonitor) ===
def record_state(
self,
position: np.ndarray,
velocity: np.ndarray,
min_obstacle_distance: float,
mpc_latency: float = 0.0,
) -> None:
"""Record state at a timestep during execution."""
self._monitor.record_state(position, velocity, min_obstacle_distance, mpc_latency)
def record_collision(self, position: np.ndarray) -> None:
"""Record a collision event."""
self._monitor.record_collision(position)
def record_planning_result(
self,
phase_name: str,
planner_type: str,
success: bool,
planning_time: float,
path: list | None = None,
) -> None:
"""Record a planning result."""
self._monitor.record_planning_result(
phase_name, planner_type, success, planning_time, path
)
def mark_goal_reached(self, goal_index: int) -> None:
"""Mark a goal as reached."""
self._monitor.mark_goal_reached(goal_index)
if 0 <= goal_index < len(self.result.reached_goals):
self.result.reached_goals[goal_index] = True
# === Finalization ===
def finalize(self, task_success: bool = None) -> BenchmarkResult:
"""Compute final metrics and return result."""
result = self.result
# Copy data from monitor
result.trajectory = self._monitor.trajectory.copy()
result.planning_records = self._monitor.planning_records.copy()
result.phase_records = self._monitor.phase_records.copy()
result.collision_events = self._monitor.collision_events.copy()
result.reached_goals = self._monitor.reached_goals.copy()
# Get statistics from monitor
stats = self._monitor.get_statistics()
# Task success
if task_success is not None:
result.task_success = task_success
else:
result.task_success = all(result.reached_goals) if result.reached_goals else False
# Copy stats
result.total_execution_time = stats.get("total_time", 0.0)
result.total_planning_time = stats.get("total_planning_time", 0.0)
result.total_path_length = stats.get("total_path_length", 0.0)
result.min_obstacle_margin = stats.get("min_obstacle_margin", float('inf'))
result.avg_obstacle_margin = stats.get("avg_obstacle_margin", 0.0)
result.safety_rate = stats.get("safety_rate", 0.0)
result.avg_mpc_latency = stats.get("avg_mpc_latency", 0.0)
result.max_mpc_latency = stats.get("max_mpc_latency", 0.0)
return result
def save_results(self) -> tuple[str, str]:
"""Save results to CSV files. Returns (summary_path, trajectory_path)."""
# Summary CSV
summary_path = self.output_dir / "results" / f"{self.scenario_id}_summary.csv"
summary_dict = self.result.to_summary_dict()
with open(summary_path, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=summary_dict.keys())
writer.writeheader()
writer.writerow(summary_dict)
# Trajectory CSV
traj_path = self.output_dir / "results" / f"{self.scenario_id}_trajectory.csv"
with open(traj_path, 'w', newline='') as f:
fieldnames = ['timestamp', 'x', 'y', 'vx', 'vy', 'min_obstacle_dist', 'mpc_latency']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for state in self.result.trajectory:
writer.writerow({
'timestamp': state.timestamp,
'x': state.position[0] if len(state.position) > 0 else 0,
'y': state.position[1] if len(state.position) > 1 else 0,
'vx': state.velocity[0] if len(state.velocity) > 0 else 0,
'vy': state.velocity[1] if len(state.velocity) > 1 else 0,
'min_obstacle_dist': state.min_obstacle_distance,
'mpc_latency': state.mpc_latency,
})
# Planning records CSV
planning_path = self.output_dir / "results" / f"{self.scenario_id}_planning.csv"
with open(planning_path, 'w', newline='') as f:
fieldnames = ['phase_name', 'planner_type', 'success', 'planning_time',
'path_length', 'num_waypoints']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for pr in self.result.planning_records:
writer.writerow({
'phase_name': pr.phase_name,
'planner_type': pr.planner_type,
'success': pr.success,
'planning_time': pr.planning_time,
'path_length': pr.path_length,
'num_waypoints': pr.num_waypoints,
})
return str(summary_path), str(traj_path)
def aggregate_results(results: list[BenchmarkResult]) -> dict[str, Any]:
"""Aggregate statistics across multiple benchmark runs."""
if not results:
return {}
n = len(results)
success_rate = sum(1 for r in results if r.task_success) / n
safety_rates = [r.safety_rate for r in results]
collision_free_rate = sum(1 for r in results if len(r.collision_events) == 0) / n
exec_times = [r.total_execution_time for r in results]
planning_times = [r.total_planning_time for r in results]
path_lengths = [r.total_path_length for r in results]
min_margins = [r.min_obstacle_margin for r in results if r.min_obstacle_margin < float('inf')]
avg_margins = [r.avg_obstacle_margin for r in results]
mpc_latencies = [r.avg_mpc_latency for r in results if r.avg_mpc_latency > 0]
return {
"num_runs": n,
"task_success_rate": success_rate,
"collision_free_rate": collision_free_rate,
"avg_safety_rate": np.mean(safety_rates),
"avg_execution_time": np.mean(exec_times),
"std_execution_time": np.std(exec_times),
"avg_planning_time": np.mean(planning_times),
"std_planning_time": np.std(planning_times),
"avg_path_length": np.mean(path_lengths),
"std_path_length": np.std(path_lengths),
"avg_min_margin": np.mean(min_margins) if min_margins else 0,
"avg_avg_margin": np.mean(avg_margins),
"avg_mpc_latency": np.mean(mpc_latencies) if mpc_latencies else 0,
}
def save_aggregate_results(
results: list[BenchmarkResult],
output_path: str,
) -> None:
"""Save aggregated results to CSV."""
# Individual results
with open(output_path, 'w', newline='') as f:
if results:
fieldnames = list(results[0].to_summary_dict().keys())
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for r in results:
writer.writerow(r.to_summary_dict())
# Aggregate summary
agg = aggregate_results(results)
summary_path = output_path.replace('.csv', '_aggregate.csv')
with open(summary_path, 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=agg.keys())
writer.writeheader()
writer.writerow(agg)