Repository navigation
Expand file tree
/
Copy pathbenchmark_runner.py
More file actions
186 lines (150 loc) · 5.41 KB
/
Copy pathbenchmark_runner.py
File metadata and controls
186 lines (150 loc) · 5.41 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
#!/usr/bin/env python3
"""
Batch benchmark runner for mobile manipulator planning.
Runs multiple scenarios with different random seeds and aggregates statistics.
Usage:
python benchmark_runner.py --runs 10 --seed 42
python benchmark_runner.py --runs 5 --output my_benchmark
"""
import argparse
import sys
import traceback
from datetime import datetime
from pathlib import Path
import numpy as np
from benchmark import BenchmarkResult, aggregate_results, save_aggregate_results
from benchmark_plots import plot_aggregate_comparison
def run_single_scenario(run_id: int, seed: int, output_dir: str) -> BenchmarkResult | None:
"""
Run a single scenario with benchmarking enabled.
Args:
run_id: Run identifier
seed: Random seed for this run
output_dir: Directory for output files
Returns:
BenchmarkResult or None if run failed
"""
# Import here to avoid loading PyBullet until needed
from main import run_planning_demo
scenario_id = f"run_{run_id:04d}_seed_{seed}"
print(f"\n{'='*60}")
print(f"Starting Run {run_id} (seed={seed})")
print(f"{'='*60}")
try:
result = run_planning_demo(
benchmark=True,
scenario_id=scenario_id,
seed=seed,
)
return result
except Exception as e:
print(f"Run {run_id} failed with error: {e}")
traceback.print_exc()
return None
def run_batch_benchmark(
num_runs: int,
base_seed: int = 42,
output_dir: str = "benchmarks",
) -> list[BenchmarkResult]:
"""
Run multiple benchmark scenarios.
Args:
num_runs: Number of scenarios to run
base_seed: Base random seed (each run uses base_seed + run_id)
output_dir: Directory for output files
Returns:
List of BenchmarkResult objects
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
results: list[BenchmarkResult] = []
successful = 0
failed = 0
print(f"\n{'#'*60}")
print(f"# Batch Benchmark: {num_runs} runs")
print(f"# Base seed: {base_seed}")
print(f"# Output: {output_path.absolute()}")
print(f"{'#'*60}")
for run_id in range(num_runs):
seed = base_seed + run_id
result = run_single_scenario(run_id, seed, str(output_path))
if result is not None:
results.append(result)
successful += 1
print(f"Run {run_id}: SUCCESS (Task: {'PASS' if result.task_success else 'FAIL'})")
else:
failed += 1
print(f"Run {run_id}: FAILED")
return results
def print_summary(results: list[BenchmarkResult]) -> None:
"""Print summary statistics from batch runs."""
if not results:
print("\nNo successful runs to summarize.")
return
agg = aggregate_results(results)
print(f"\n{'='*60}")
print("BATCH BENCHMARK SUMMARY")
print(f"{'='*60}")
print(f"Total runs: {agg['num_runs']}")
print(f"Task success rate: {agg['task_success_rate']*100:.1f}%")
print(f"Collision-free rate: {agg['collision_free_rate']*100:.1f}%")
print(f"Average safety rate: {agg['avg_safety_rate']*100:.1f}%")
print()
print("Timing Statistics:")
print(f" Execution time: {agg['avg_execution_time']:.2f} +/- {agg['std_execution_time']:.2f}s")
print(f" Planning time: {agg['avg_planning_time']:.2f} +/- {agg['std_planning_time']:.2f}s")
print(f" Path length: {agg['avg_path_length']:.2f} +/- {agg['std_path_length']:.2f}m")
print()
print("Safety Statistics:")
print(f" Avg min margin: {agg['avg_min_margin']:.3f}m")
print(f" Avg avg margin: {agg['avg_avg_margin']:.3f}m")
print(f" Avg MPC latency: {agg['avg_mpc_latency']*1000:.2f}ms")
print(f"{'='*60}")
def main():
parser = argparse.ArgumentParser(
description="Run batch benchmarks for mobile manipulator planning"
)
parser.add_argument(
"--runs", type=int, default=10,
help="Number of benchmark runs (default: 10)"
)
parser.add_argument(
"--seed", type=int, default=42,
help="Base random seed (default: 42)"
)
parser.add_argument(
"--output", type=str, default="benchmarks",
help="Output directory (default: benchmarks)"
)
parser.add_argument(
"--no-plots", action="store_true",
help="Skip generating comparison plots"
)
args = parser.parse_args()
# Run batch benchmark
results = run_batch_benchmark(
num_runs=args.runs,
base_seed=args.seed,
output_dir=args.output,
)
# Print summary
print_summary(results)
if not results:
print("\nNo successful runs. Exiting.")
return 1
# Save aggregate results
output_path = Path(args.output)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
aggregate_csv = output_path / "results" / f"batch_{timestamp}_results.csv"
aggregate_csv.parent.mkdir(parents=True, exist_ok=True)
save_aggregate_results(results, str(aggregate_csv))
print(f"\nAggregate results saved to: {aggregate_csv}")
# Generate comparison plots
if not args.no_plots:
comparison_plot = output_path / "plots" / f"batch_{timestamp}_comparison.png"
comparison_plot.parent.mkdir(parents=True, exist_ok=True)
plot_aggregate_comparison(results, str(comparison_plot))
print(f"Comparison plot saved to: {comparison_plot}")
return 0
if __name__ == "__main__":
sys.exit(main())