Repository navigation
Expand file tree
/
Copy pathbenchmark_plots.py
More file actions
950 lines (820 loc) · 27.4 KB
/
Copy pathbenchmark_plots.py
File metadata and controls
950 lines (820 loc) · 27.4 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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
"""Visualization functions for benchmarking."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from benchmark import BenchmarkResult
from sim2d.world import World2D
def plot_trajectory_2d(
result: "BenchmarkResult",
world2d: "World2D" = None,
planned_paths: list[list[np.ndarray]] = None,
moving_obstacle_paths: list[np.ndarray] = None,
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot 2D bird's eye view of the trajectory (top-down map view).
Args:
result: Benchmark result with trajectory data
world2d: Optional 2D world for obstacle visualization
planned_paths: Optional list of planned paths for comparison
moving_obstacle_paths: Optional list of moving obstacle trajectories
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
except ImportError:
print("matplotlib not installed; skipping plot.")
return
fig, ax = plt.subplots(figsize=(12, 12))
# Plot world obstacles (no inflation - show actual obstacle sizes)
if world2d is not None:
try:
world2d.plot(ax, robot_radius=0.0)
except Exception as e:
print(f"Warning: Could not plot world: {e}")
# Extract trajectory positions
if result.trajectory:
positions = np.array([s.position[:2] for s in result.trajectory])
# Plot actual trajectory with gradient color based on time
n_points = len(positions)
if n_points > 1:
# Create segments colored by progress
for i in range(n_points - 1):
progress = i / n_points
color = plt.cm.Blues(0.3 + 0.7 * progress)
ax.plot(
positions[i : i + 2, 0],
positions[i : i + 2, 1],
"-",
color=color,
linewidth=3,
zorder=10,
)
# Start marker
ax.scatter(
[positions[0, 0]],
[positions[0, 1]],
c="lime",
s=250,
marker="o",
edgecolors="black",
linewidth=2,
label="Start",
zorder=20,
)
# End marker
ax.scatter(
[positions[-1, 0]],
[positions[-1, 1]],
c="red",
s=250,
marker="s",
edgecolors="black",
linewidth=2,
label="End",
zorder=20,
)
# Plot goal positions
if result.goal_positions:
for i, goal in enumerate(result.goal_positions):
reached = (
result.reached_goals[i] if i < len(result.reached_goals) else False
)
color = "gold" if reached else "orange"
ax.scatter(
[goal[0]],
[goal[1]],
c=color,
s=300,
marker="*",
edgecolors="black",
linewidth=1.5,
label=f"Goal {i + 1} ({'reached' if reached else 'missed'})",
zorder=15,
)
# Plot moving obstacle paths
if moving_obstacle_paths:
for i, obs_path in enumerate(moving_obstacle_paths):
if len(obs_path) > 0:
ax.plot(
obs_path[:, 0],
obs_path[:, 1],
"r--",
linewidth=1.5,
alpha=0.6,
label="Moving obstacles" if i == 0 else None,
)
# Draw circles at intervals
for idx in np.linspace(
0, len(obs_path) - 1, min(5, len(obs_path)), dtype=int
):
ax.add_patch(
Circle(
obs_path[idx], 0.25, fill=False, edgecolor="red", alpha=0.4
)
)
# Plot collision events
if result.collision_events:
coll_positions = np.array([e[1][:2] for e in result.collision_events])
ax.scatter(
coll_positions[:, 0],
coll_positions[:, 1],
c="red",
s=100,
marker="X",
label="Collisions",
zorder=25,
)
# Add stats text box
stats_text = (
f"Task: {'SUCCESS' if result.task_success else 'FAILED'}\n"
f"Path length: {result.total_path_length:.1f}m\n"
f"Exec time: {result.total_execution_time:.1f}s\n"
f"Safety rate: {result.safety_rate * 100:.1f}%"
)
ax.text(
0.02,
0.98,
stats_text,
transform=ax.transAxes,
fontsize=10,
verticalalignment="top",
bbox=dict(boxstyle="round", facecolor="white", alpha=0.9),
zorder=30,
)
ax.set_xlabel("X (m)", fontsize=12)
ax.set_ylabel("Y (m)", fontsize=12)
ax.set_title(f"Top-Down Map View - Scenario {result.scenario_id}", fontsize=14)
ax.legend(loc="upper right", fontsize=9)
ax.set_aspect("equal")
ax.grid(True, alpha=0.3)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved trajectory plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def plot_time_series(
result: "BenchmarkResult",
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot time series: position, velocity, and obstacle distance.
Args:
result: Benchmark result with trajectory data
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not installed; skipping plot.")
return
if not result.trajectory:
print("No trajectory data to plot.")
return
timestamps = np.array([s.timestamp for s in result.trajectory])
positions = np.array([s.position[:2] for s in result.trajectory])
velocities = np.array([s.velocity[:2] for s in result.trajectory])
vel_magnitudes = np.linalg.norm(velocities, axis=1)
obstacle_dists = np.array([s.min_obstacle_distance for s in result.trajectory])
fig, axes = plt.subplots(3, 1, figsize=(12, 10), sharex=True)
# Position plot
ax1 = axes[0]
ax1.plot(timestamps, positions[:, 0], "b-", label="X")
ax1.plot(timestamps, positions[:, 1], "r-", label="Y")
ax1.set_ylabel("Position (m)")
ax1.set_title(f"Time Series - Scenario {result.scenario_id}")
ax1.legend()
ax1.grid(True, alpha=0.3)
# Velocity plot
ax2 = axes[1]
ax2.plot(timestamps, velocities[:, 0], "b-", label="Vx", alpha=0.7)
ax2.plot(timestamps, velocities[:, 1], "r-", label="Vy", alpha=0.7)
ax2.plot(timestamps, vel_magnitudes, "k-", linewidth=2, label="|V|")
ax2.set_ylabel("Velocity (m/s)")
ax2.legend()
ax2.grid(True, alpha=0.3)
# Obstacle distance plot
ax3 = axes[2]
ax3.plot(timestamps, obstacle_dists, "g-", linewidth=2)
ax3.axhline(y=0.1, color="r", linestyle="--", label="Safety margin")
ax3.fill_between(timestamps, 0, obstacle_dists, alpha=0.3, color="green")
ax3.set_ylabel("Min Obstacle Distance (m)")
ax3.set_xlabel("Time (s)")
ax3.legend()
ax3.grid(True, alpha=0.3)
ax3.set_ylim(bottom=0)
# Mark collision events
if result.collision_events:
for t, _ in result.collision_events:
for ax in axes:
ax.axvline(x=t, color="red", linestyle="-", alpha=0.5)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved time series plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def plot_obstacle_margin(
result: "BenchmarkResult",
safety_margin: float = 0.1,
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot obstacle distance margin over time with safety analysis.
Args:
result: Benchmark result with trajectory data
safety_margin: Threshold for safety (meters)
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
except ImportError:
print("matplotlib not installed; skipping plot.")
return
if not result.trajectory:
print("No trajectory data to plot.")
return
timestamps = np.array([s.timestamp for s in result.trajectory])
obstacle_dists = np.array([s.min_obstacle_distance for s in result.trajectory])
fig, ax = plt.subplots(figsize=(12, 6))
# Create color-coded segments
safe_mask = obstacle_dists > safety_margin
unsafe_mask = ~safe_mask
# Plot safe regions
ax.fill_between(
timestamps,
0,
obstacle_dists,
where=safe_mask,
alpha=0.4,
color="green",
label="Safe",
)
# Plot unsafe regions
ax.fill_between(
timestamps,
0,
obstacle_dists,
where=unsafe_mask,
alpha=0.4,
color="red",
label="Unsafe",
)
# Plot line
ax.plot(timestamps, obstacle_dists, "k-", linewidth=1.5)
# Safety threshold line
ax.axhline(
y=safety_margin,
color="orange",
linestyle="--",
linewidth=2,
label=f"Safety threshold ({safety_margin}m)",
)
# Mark minimum point
min_idx = np.argmin(obstacle_dists)
ax.scatter(
[timestamps[min_idx]],
[obstacle_dists[min_idx]],
c="purple",
s=100,
marker="v",
zorder=10,
label=f"Min: {obstacle_dists[min_idx]:.3f}m",
)
# Mark collision events
if result.collision_events:
for t, _ in result.collision_events:
ax.axvline(x=t, color="red", linestyle="-", linewidth=2, alpha=0.7)
ax.scatter([], [], c="red", marker="|", s=200, label="Collision event")
# Statistics box
stats_text = (
f"Min margin: {result.min_obstacle_margin:.3f}m\n"
f"Avg margin: {result.avg_obstacle_margin:.3f}m\n"
f"Safety rate: {result.safety_rate * 100:.1f}%\n"
f"Collisions: {len(result.collision_events)}"
)
ax.text(
0.02,
0.98,
stats_text,
transform=ax.transAxes,
fontsize=10,
verticalalignment="top",
bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Distance to Nearest Obstacle (m)")
ax.set_title(f"Obstacle Safety Margin - Scenario {result.scenario_id}")
ax.legend(loc="upper right")
ax.grid(True, alpha=0.3)
ax.set_ylim(bottom=0)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved obstacle margin plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def plot_mpc_latency(
result: "BenchmarkResult",
target_dt: float = 0.01,
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot MPC solver latency over time.
Args:
result: Benchmark result with trajectory data
target_dt: Target timestep for comparison
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not installed; skipping plot.")
return
latency_data = [
(s.timestamp, s.mpc_latency) for s in result.trajectory if s.mpc_latency > 0
]
if not latency_data:
print("No MPC latency data to plot.")
return
timestamps, latencies = zip(*latency_data)
timestamps = np.array(timestamps)
latencies = np.array(latencies) * 1000 # Convert to ms
fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(timestamps, latencies, "b-", linewidth=1, alpha=0.7)
ax.scatter(timestamps, latencies, c="blue", s=5, alpha=0.5)
# Target line
target_ms = target_dt * 1000
ax.axhline(
y=target_ms,
color="red",
linestyle="--",
linewidth=2,
label=f"Target dt ({target_ms:.1f}ms)",
)
# Statistics
avg_lat = np.mean(latencies)
max_lat = np.max(latencies)
ax.axhline(
y=avg_lat,
color="green",
linestyle=":",
linewidth=1.5,
label=f"Average ({avg_lat:.2f}ms)",
)
stats_text = (
f"Avg: {avg_lat:.2f}ms\n"
f"Max: {max_lat:.2f}ms\n"
f"Violations: {np.sum(latencies > target_ms)}"
)
ax.text(
0.02,
0.98,
stats_text,
transform=ax.transAxes,
fontsize=10,
verticalalignment="top",
bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
)
ax.set_xlabel("Time (s)")
ax.set_ylabel("MPC Latency (ms)")
ax.set_title(f"MPC Solver Latency - Scenario {result.scenario_id}")
ax.legend(loc="upper right")
ax.grid(True, alpha=0.3)
ax.set_ylim(bottom=0)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved MPC latency plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def generate_all_plots(
result: "BenchmarkResult",
output_dir: str,
world2d: "World2D" = None,
planned_paths: list[list[np.ndarray]] = None,
moving_obstacle_paths: list[np.ndarray] = None,
show: bool = False,
) -> list[str]:
"""
Generate all benchmark plots.
Args:
result: Benchmark result with trajectory data
output_dir: Directory to save plots
world2d: Optional 2D world for obstacle visualization
planned_paths: Optional list of planned paths
moving_obstacle_paths: Optional moving obstacle trajectories
show: Whether to display plots
Returns:
List of saved plot paths
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
saved_paths = []
# Top-down map/trajectory plot
try:
traj_path = output_dir / f"{result.scenario_id}_map.png"
plot_trajectory_2d(
result, world2d, planned_paths, moving_obstacle_paths, str(traj_path), show
)
saved_paths.append(str(traj_path))
except Exception as e:
print(f"Warning: Could not generate map plot: {e}")
# Time series plot
try:
ts_path = output_dir / f"{result.scenario_id}_timeseries.png"
plot_time_series(result, str(ts_path), show)
saved_paths.append(str(ts_path))
except Exception as e:
print(f"Warning: Could not generate time series plot: {e}")
# Obstacle margin plot
try:
margin_path = output_dir / f"{result.scenario_id}_margin.png"
plot_obstacle_margin(result, output_path=str(margin_path), show=show)
saved_paths.append(str(margin_path))
except Exception as e:
print(f"Warning: Could not generate margin plot: {e}")
# MPC latency plot
try:
latency_path = output_dir / f"{result.scenario_id}_mpc_latency.png"
plot_mpc_latency(result, output_path=str(latency_path), show=show)
saved_paths.append(str(latency_path))
except Exception as e:
print(f"Warning: Could not generate MPC latency plot: {e}")
# Planning times plot (RRT/OMPL latency)
try:
planning_path = output_dir / f"{result.scenario_id}_planning.png"
plot_planning_times(result, output_path=str(planning_path), show=show)
saved_paths.append(str(planning_path))
except Exception as e:
print(f"Warning: Could not generate planning times plot: {e}")
return saved_paths
def plot_planning_times(
result: "BenchmarkResult",
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot planning times for each phase (RRT*, OMPL).
Args:
result: Benchmark result with planning data
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not installed; skipping plot.")
return
if not result.planning_records:
print("No planning data to plot.")
return
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Left: Bar chart of planning times
ax1 = axes[0]
phases = [pr.phase_name for pr in result.planning_records]
times = [pr.planning_time for pr in result.planning_records]
planners = [pr.planner_type for pr in result.planning_records]
colors = ["tab:blue" if p == "rrt_star" else "tab:orange" for p in planners]
bars = ax1.bar(phases, times, color=colors, edgecolor="black", alpha=0.8)
# Add value labels on bars
for bar, t, planner in zip(bars, times, planners):
ax1.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + 0.1,
f"{t:.2f}s\n({planner})",
ha="center",
va="bottom",
fontsize=9,
)
ax1.set_xlabel("Planning Phase")
ax1.set_ylabel("Planning Time (s)")
ax1.set_title("Planning Time per Phase")
ax1.tick_params(axis="x", rotation=15)
# Add legend for planner types
from matplotlib.patches import Patch
legend_elements = [
Patch(facecolor="tab:blue", edgecolor="black", label="RRT*"),
Patch(facecolor="tab:orange", edgecolor="black", label="OMPL"),
]
ax1.legend(handles=legend_elements, loc="upper right")
# Right: Path length vs planning time scatter
ax2 = axes[1]
path_lengths = [pr.path_length for pr in result.planning_records]
for i, pr in enumerate(result.planning_records):
color = "tab:blue" if pr.planner_type == "rrt_star" else "tab:orange"
marker = "o" if pr.success else "x"
ax2.scatter(
pr.planning_time,
pr.path_length,
c=color,
marker=marker,
s=150,
edgecolors="black",
linewidth=1.5,
label=pr.phase_name,
)
ax2.set_xlabel("Planning Time (s)")
ax2.set_ylabel("Path Length (m)")
ax2.set_title("Path Length vs Planning Time")
ax2.legend(loc="upper left", fontsize=8)
ax2.grid(True, alpha=0.3)
# Add total stats
total_planning = sum(times)
fig.suptitle(
f"Planning Performance - Total: {total_planning:.2f}s", fontsize=12, y=1.02
)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved planning times plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def plot_aggregate_comparison(
results: list["BenchmarkResult"],
output_path: str = None,
show: bool = False,
) -> None:
"""
Plot comparison across multiple benchmark runs.
Args:
results: List of benchmark results
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib not installed; skipping plot.")
return
if not results:
print("No results to compare.")
return
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Success rate bar chart
ax1 = axes[0, 0]
success_count = sum(1 for r in results if r.task_success)
ax1.bar(
["Success", "Failure"],
[success_count, len(results) - success_count],
color=["green", "red"],
)
ax1.set_ylabel("Count")
ax1.set_title(f"Task Success Rate: {success_count / len(results) * 100:.1f}%")
# Execution time distribution
ax2 = axes[0, 1]
exec_times = [r.total_execution_time for r in results]
ax2.hist(
exec_times,
bins=min(20, len(results)),
color="blue",
alpha=0.7,
edgecolor="black",
)
ax2.axvline(
np.mean(exec_times),
color="red",
linestyle="--",
label=f"Mean: {np.mean(exec_times):.2f}s",
)
ax2.set_xlabel("Execution Time (s)")
ax2.set_ylabel("Count")
ax2.set_title("Execution Time Distribution")
ax2.legend()
# Safety rate distribution
ax3 = axes[1, 0]
safety_rates = [r.safety_rate * 100 for r in results]
ax3.hist(
safety_rates,
bins=min(20, len(results)),
color="green",
alpha=0.7,
edgecolor="black",
)
ax3.axvline(
np.mean(safety_rates),
color="red",
linestyle="--",
label=f"Mean: {np.mean(safety_rates):.1f}%",
)
ax3.set_xlabel("Safety Rate (%)")
ax3.set_ylabel("Count")
ax3.set_title("Safety Rate Distribution")
ax3.legend()
# Min obstacle margin scatter
ax4 = axes[1, 1]
run_ids = range(len(results))
min_margins = [r.min_obstacle_margin for r in results]
colors = ["green" if r.task_success else "red" for r in results]
ax4.scatter(run_ids, min_margins, c=colors, alpha=0.7, s=50)
ax4.axhline(0.1, color="orange", linestyle="--", label="Safety threshold")
ax4.set_xlabel("Run ID")
ax4.set_ylabel("Min Obstacle Margin (m)")
ax4.set_title("Minimum Obstacle Margin per Run")
ax4.legend()
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=150, bbox_inches="tight")
print(f"Saved aggregate comparison plot: {output_path}")
if show:
plt.show()
else:
plt.close(fig)
def plot_trajectory_on_map(
world2d: "World2D",
planned_path: list,
actual_trajectory: list = None,
layout: list[str] | None = None,
goal_positions: list[tuple[float, float]] | None = None,
target_positions: list[tuple[float, float]] | None = None,
moving_obstacles: list | None = None,
collision_positions: list[tuple[float, float]] | None = None,
output_path: str = None,
show: bool = False,
) -> None:
"""
Simple plot of planned path and actual trajectory on 2D map.
Args:
world2d: 2D world for obstacle visualization
planned_path: List of (x, y) waypoints from planner
actual_trajectory: List of (x, y) positions from execution
layout: Layout grid for goal shelves
goal_positions: Optional goal/subgoal positions
target_positions: Optional target block positions
moving_obstacles: Optional list of moving obstacles
collision_positions: Optional collision points
output_path: Path to save the plot
show: Whether to display the plot
"""
try:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
except ImportError:
print("matplotlib not installed; skipping plot.")
return
fig, ax = plt.subplots(figsize=(10, 10))
# Plot obstacles
if world2d is not None:
try:
world2d.plot(ax, robot_radius=0.0)
except Exception as e:
print(f"Warning: Could not plot world: {e}")
# Plot goal shelves in green
if layout:
import config
from matplotlib.patches import Rectangle
x_offset = -(len(layout[0]) * config.CELL_SIZE) / 2
y_offset = -(len(layout) * config.CELL_SIZE) / 2
shelf_size = config.SHELF_FOOTPRINT_SIZE
label_added = False
for r, row in enumerate(layout):
for c, symbol in enumerate(row):
if symbol not in ["G", "2"]:
continue
x = x_offset + (c * config.CELL_SIZE)
y = y_offset + (r * config.CELL_SIZE)
ax.add_patch(
Rectangle(
(x - shelf_size / 2, y - shelf_size / 2),
shelf_size,
shelf_size,
facecolor="green",
edgecolor="black",
alpha=0.8,
zorder=12,
label="Goal shelf" if not label_added else None,
)
)
label_added = True
if goal_positions:
for idx, goal in enumerate(goal_positions):
ax.scatter(
[goal[0]],
[goal[1]],
c="yellow",
s=140,
marker="*",
edgecolors="black",
linewidth=1.2,
label="Subgoal" if idx == 0 else None,
zorder=13,
)
if target_positions:
import config
from matplotlib.patches import Rectangle
half_size = float(config.OBJECT_HALF_SIZE)
label_added = False
for target in target_positions:
ax.add_patch(
Rectangle(
(target[0] - half_size, target[1] - half_size),
2 * half_size,
2 * half_size,
facecolor="blue",
edgecolor="black",
alpha=0.9,
zorder=13,
label="Target" if not label_added else None,
)
)
label_added = True
if moving_obstacles:
import config
from matplotlib.patches import Circle
if actual_trajectory and len(actual_trajectory) > 1:
duration = (len(actual_trajectory) - 1) * config.SIMULATION_DT
else:
duration = 10.0
num_samples = max(20, min(200, int(duration / config.SIMULATION_DT)))
t_values = np.linspace(0.0, duration, num=num_samples)
for idx, obs in enumerate(moving_obstacles):
centers = np.array([obs.center(t) for t in t_values], dtype=float)
ax.plot(
centers[:, 0],
centers[:, 1],
linestyle=":",
linewidth=1.4,
color="orange",
alpha=0.7,
label="Cone path" if idx == 0 else None,
)
center = obs.center(0.0)
ax.scatter(
[center[0]],
[center[1]],
c="orange",
s=80,
marker="x",
label="Cone" if idx == 0 else None,
zorder=11,
)
ax.add_patch(
Circle(
(center[0], center[1]),
float(obs.radius),
fill=False,
edgecolor="orange",
linewidth=1.2,
alpha=0.8,
)
)
if collision_positions:
coll_arr = np.array(collision_positions, dtype=float)
if len(coll_arr) > 0:
ax.scatter(
coll_arr[:, 0],
coll_arr[:, 1],
c="red",
s=120,
marker="X",
edgecolors="black",
linewidth=1.2,
label="Collision" if len(coll_arr) else None,
zorder=14,
)
# Plot actual trajectory
if actual_trajectory and len(actual_trajectory) > 0:
traj_arr = np.array(actual_trajectory)
ax.plot(
traj_arr[:, 0],
traj_arr[:, 1],
"r-",
linewidth=1.5,
label="Actual",
alpha=0.8,
)
ax.set_xlabel("X (m)")
ax.set_ylabel("Y (m)")
ax.set_aspect("equal")
ax.legend(loc="upper right")
ax.grid(True, alpha=0.3)
plt.tight_layout()
if output_path:
fig.savefig(output_path, dpi=100, bbox_inches="tight")
if show:
plt.show()
else:
plt.close(fig)