Repository navigation
Expand file tree
/
Copy pathplanner_comparison.py
More file actions
2267 lines (1961 loc) · 77.3 KB
/
Copy pathplanner_comparison.py
File metadata and controls
2267 lines (1961 loc) · 77.3 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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Planner Comparison Benchmark for Mobile Manipulator Planning.
Compares Custom RRT*, OMPL RRT*, and OMPL RRT-Connect planners
across multiple random seeds.
Usage:
python planner_comparison.py --runs 20 --seed 42
python planner_comparison.py --runs 100 --seed 0 --timeout 30
"""
import argparse
import csv
import io
import os
import sys
import time
import random
import traceback
from contextlib import redirect_stdout, redirect_stderr
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Optional, Sequence
import numpy as np
class SuppressOutput:
"""Context manager to suppress stdout/stderr."""
def __init__(self, suppress: bool = True):
self.suppress = suppress
self._stdout = None
self._stderr = None
self._devnull = None
def __enter__(self):
if self.suppress:
self._stdout = sys.stdout
self._stderr = sys.stderr
self._devnull = open(os.devnull, "w")
sys.stdout = self._devnull
sys.stderr = self._devnull
return self
def __exit__(self, *args):
if self.suppress:
sys.stdout = self._stdout
sys.stderr = self._stderr
if self._devnull:
self._devnull.close()
PLANNING_PHASES = ["base_path_1", "arm_path_1", "base_path_2", "arm_path_2"]
@dataclass
class PlannerRunResult:
"""Result from a single planner run."""
planner_name: str
seed: int
run_id: int
# Planning metrics
planning_success: bool = False
planning_time: float = 0.0
path_length: float = 0.0
num_waypoints: int = 0
phase_success: dict[str, bool] = field(default_factory=dict)
phase_planning_time: dict[str, float] = field(default_factory=dict)
phase_path_length: dict[str, float] = field(default_factory=dict)
# Execution metrics (if execution was run)
execution_success: bool = False
execution_time: float = 0.0
collision_count: int = 0
safety_rate: float = 0.0
min_obstacle_margin: float = float("inf")
avg_obstacle_margin: float = 0.0
# Error info
error_message: str = ""
def to_dict(self) -> dict[str, Any]:
data = {
"planner_name": self.planner_name,
"seed": self.seed,
"run_id": self.run_id,
"planning_success": self.planning_success,
"planning_time": self.planning_time,
"path_length": self.path_length,
"num_waypoints": self.num_waypoints,
"execution_success": self.execution_success,
"execution_time": self.execution_time,
"collision_count": self.collision_count,
"safety_rate": self.safety_rate,
"min_obstacle_margin": self.min_obstacle_margin,
"avg_obstacle_margin": self.avg_obstacle_margin,
"error_message": self.error_message,
}
for phase in PLANNING_PHASES:
data[f"{phase}_success"] = self.phase_success.get(phase, False)
data[f"{phase}_planning_time"] = self.phase_planning_time.get(phase, 0.0)
data[f"{phase}_path_length"] = self.phase_path_length.get(phase, 0.0)
return data
@dataclass
class PlannerStats:
"""Aggregated statistics for a planner."""
planner_name: str
num_runs: int = 0
# Planning stats
planning_success_rate: float = 0.0
avg_planning_time: float = 0.0
std_planning_time: float = 0.0
avg_path_length: float = 0.0
std_path_length: float = 0.0
# Execution stats
execution_success_rate: float = 0.0
avg_execution_time: float = 0.0
std_execution_time: float = 0.0
collision_free_rate: float = 0.0
avg_safety_rate: float = 0.0
avg_min_margin: float = 0.0
avg_avg_margin: float = 0.0
# Phase stats
phase_success_rate: dict[str, float] = field(default_factory=dict)
phase_avg_planning_time: dict[str, float] = field(default_factory=dict)
phase_std_planning_time: dict[str, float] = field(default_factory=dict)
phase_avg_path_length: dict[str, float] = field(default_factory=dict)
phase_std_path_length: dict[str, float] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
data = {
"planner_name": self.planner_name,
"num_runs": self.num_runs,
"planning_success_rate": self.planning_success_rate,
"avg_planning_time": self.avg_planning_time,
"std_planning_time": self.std_planning_time,
"avg_path_length": self.avg_path_length,
"std_path_length": self.std_path_length,
"execution_success_rate": self.execution_success_rate,
"avg_execution_time": self.avg_execution_time,
"std_execution_time": self.std_execution_time,
"collision_free_rate": self.collision_free_rate,
"avg_safety_rate": self.avg_safety_rate,
"avg_min_margin": self.avg_min_margin,
"avg_avg_margin": self.avg_avg_margin,
}
for phase in PLANNING_PHASES:
data[f"{phase}_success_rate"] = self.phase_success_rate.get(phase, 0.0)
data[f"{phase}_avg_time"] = self.phase_avg_planning_time.get(phase, 0.0)
data[f"{phase}_std_time"] = self.phase_std_planning_time.get(phase, 0.0)
data[f"{phase}_avg_length"] = self.phase_avg_path_length.get(phase, 0.0)
data[f"{phase}_std_length"] = self.phase_std_path_length.get(phase, 0.0)
return data
def compute_path_length(path: list) -> float:
"""Compute total path length from waypoints."""
if not path or len(path) < 2:
return 0.0
total = 0.0
for i in range(1, len(path)):
if len(path[i]) >= 2 and len(path[i - 1]) >= 2:
dx = path[i][0] - path[i - 1][0]
dy = path[i][1] - path[i - 1][1]
total += np.sqrt(dx * dx + dy * dy)
return total
class _RRTNode2D:
__slots__ = ("config", "parent", "cost", "children")
def __init__(
self,
config: np.ndarray,
parent: Optional["_RRTNode2D"] = None,
cost: float = 0.0,
):
self.config = config
self.parent = parent
self.cost = cost
self.children: list[_RRTNode2D] = []
def _interpolate_path_2d(path: list[np.ndarray], num_points: int) -> list[list[float]]:
if len(path) < 2:
return [p.tolist() for p in path]
total_length = sum(
float(np.linalg.norm(path[i + 1] - path[i])) for i in range(len(path) - 1)
)
if total_length < 1e-6:
return [p.tolist() for p in path]
result = [path[0]]
step = total_length / (num_points - 1)
segment_idx = 0
segment_start_dist = 0.0
for i in range(1, num_points - 1):
target_dist = i * step
while segment_idx < len(path) - 1:
seg_len = float(np.linalg.norm(path[segment_idx + 1] - path[segment_idx]))
if segment_start_dist + seg_len >= target_dist:
break
segment_start_dist += seg_len
segment_idx += 1
if segment_idx >= len(path) - 1:
break
seg_len = float(np.linalg.norm(path[segment_idx + 1] - path[segment_idx]))
if seg_len < 1e-6:
result.append(path[segment_idx])
continue
t = (target_dist - segment_start_dist) / seg_len
interp = path[segment_idx] + t * (path[segment_idx + 1] - path[segment_idx])
result.append(interp)
result.append(path[-1])
return [p.tolist() for p in result]
def _sample_free_2d(
bounds: tuple[float, float, float, float],
rng: np.random.Generator,
*,
is_state_valid: Any,
max_tries: int = 10000,
) -> np.ndarray:
xmin, xmax, ymin, ymax = bounds
for _ in range(int(max_tries)):
x = rng.uniform(xmin, xmax)
y = rng.uniform(ymin, ymax)
p = np.array([x, y], dtype=float)
if is_state_valid(p):
return p
raise RuntimeError("Failed to sample a collision-free point")
def _segment_is_collision_free_2d(
a: np.ndarray,
b: np.ndarray,
*,
is_state_valid: Any,
) -> bool:
import config
dist = float(np.linalg.norm(b - a))
step = max(0.05, config.CELL_SIZE * 0.25)
steps = max(2, int(dist / step))
for i in range(steps + 1):
t = i / steps
p = a + t * (b - a)
if not is_state_valid(p):
return False
return True
def _extract_path_2d(node: _RRTNode2D) -> list[np.ndarray]:
path = []
current = node
while current is not None:
path.append(current.config)
current = current.parent
path.reverse()
return path
def _plan_rrt_star_2d(
start_xy: np.ndarray,
goal_xy: np.ndarray,
timeout: float,
rng: np.random.Generator,
*,
bounds: tuple[float, float, float, float],
is_state_valid: Any,
) -> tuple[list[list[float]] | None, str]:
import config
if not is_state_valid(start_xy):
return None, "invalid start state"
if not is_state_valid(goal_xy):
return None, "invalid goal state"
step_size = config.PLANNER_RANGE
goal_bias = getattr(config, "RRT_GOAL_BIAS", 0.05)
rewire_radius = getattr(config, "RRT_REWIRE_RADIUS", 0.5)
goal_threshold = getattr(config, "RRT_GOAL_THRESHOLD", 0.1)
start_node = _RRTNode2D(start_xy, None, 0.0)
nodes = [start_node]
goal_node: Optional[_RRTNode2D] = None
best_cost = float("inf")
start_time = time.time()
def distance(a: np.ndarray, b: np.ndarray) -> float:
return float(np.linalg.norm(a - b))
def steer(a: np.ndarray, b: np.ndarray) -> np.ndarray:
dist = distance(a, b)
if dist <= step_size:
return b.copy()
ratio = step_size / dist
return a + ratio * (b - a)
while time.time() - start_time < timeout:
if rng.random() < goal_bias:
q_rand = goal_xy
else:
q_rand = _sample_free_2d(bounds, rng, is_state_valid=is_state_valid)
nearest = min(nodes, key=lambda n: distance(n.config, q_rand))
q_new = steer(nearest.config, q_rand)
if not _segment_is_collision_free_2d(
nearest.config, q_new, is_state_valid=is_state_valid
):
continue
near_nodes = [n for n in nodes if distance(n.config, q_new) <= rewire_radius]
best_parent = nearest
best_cost_to_new = nearest.cost + distance(nearest.config, q_new)
for near_node in near_nodes:
cand_cost = near_node.cost + distance(near_node.config, q_new)
if cand_cost < best_cost_to_new and _segment_is_collision_free_2d(
near_node.config, q_new, is_state_valid=is_state_valid
):
best_parent = near_node
best_cost_to_new = cand_cost
new_node = _RRTNode2D(q_new, best_parent, best_cost_to_new)
best_parent.children.append(new_node)
nodes.append(new_node)
for near_node in near_nodes:
if near_node is best_parent:
continue
new_cost = new_node.cost + distance(new_node.config, near_node.config)
if new_cost < near_node.cost and _segment_is_collision_free_2d(
new_node.config, near_node.config, is_state_valid=is_state_valid
):
if near_node.parent:
near_node.parent.children.remove(near_node)
near_node.parent = new_node
near_node.cost = new_cost
new_node.children.append(near_node)
dist_to_goal = distance(q_new, goal_xy)
if dist_to_goal < goal_threshold and _segment_is_collision_free_2d(
q_new, goal_xy, is_state_valid=is_state_valid
):
goal_cost = new_node.cost + dist_to_goal
if goal_cost < best_cost:
goal_node = _RRTNode2D(goal_xy, new_node, goal_cost)
path = _extract_path_2d(goal_node)
return _interpolate_path_2d(path, config.PATH_INTERPOLATION_STEPS), ""
return None, "no path"
def _plan_rrt_connect_2d(
start_xy: np.ndarray,
goal_xy: np.ndarray,
timeout: float,
rng: np.random.Generator,
*,
bounds: tuple[float, float, float, float],
is_state_valid: Any,
) -> tuple[list[list[float]] | None, str]:
import config
if not is_state_valid(start_xy):
return None, "invalid start state"
if not is_state_valid(goal_xy):
return None, "invalid goal state"
step_size = config.PLANNER_RANGE
goal_bias = getattr(config, "RRT_GOAL_BIAS", 0.05)
def distance(a: np.ndarray, b: np.ndarray) -> float:
return float(np.linalg.norm(a - b))
def steer(a: np.ndarray, b: np.ndarray) -> np.ndarray:
dist = distance(a, b)
if dist <= step_size:
return b.copy()
ratio = step_size / dist
return a + ratio * (b - a)
def extend(tree: list[_RRTNode2D], target: np.ndarray) -> Optional[_RRTNode2D]:
nearest = min(tree, key=lambda n: distance(n.config, target))
q_new = steer(nearest.config, target)
if not _segment_is_collision_free_2d(
nearest.config, q_new, is_state_valid=is_state_valid
):
return None
node = _RRTNode2D(
q_new, nearest, nearest.cost + distance(nearest.config, q_new)
)
nearest.children.append(node)
tree.append(node)
return node
def connect(tree: list[_RRTNode2D], target: np.ndarray) -> Optional[_RRTNode2D]:
node: Optional[_RRTNode2D] = None
while True:
new_node = extend(tree, target)
if not new_node:
return None
node = new_node
if distance(node.config, target) <= step_size:
return node
start_node = _RRTNode2D(start_xy, None, 0.0)
goal_node = _RRTNode2D(goal_xy, None, 0.0)
tree_a = [start_node]
tree_b = [goal_node]
start_time = time.time()
while time.time() - start_time < timeout:
if rng.random() < goal_bias:
q_rand = goal_xy
else:
q_rand = _sample_free_2d(bounds, rng, is_state_valid=is_state_valid)
new_node = extend(tree_a, q_rand)
if new_node:
connect_node = connect(tree_b, new_node.config)
if connect_node:
path_a = _extract_path_2d(new_node)
path_b = _extract_path_2d(connect_node)
path_b.reverse()
combined = path_a + path_b[1:]
if distance(combined[0], start_xy) > distance(combined[-1], start_xy):
combined.reverse()
return _interpolate_path_2d(
combined, config.PATH_INTERPOLATION_STEPS
), ""
tree_a, tree_b = tree_b, tree_a
return None, "no path"
def _base_goal_reached(
current_config: Sequence[float],
goal_config: Sequence[float],
threshold: float = 0.3,
) -> bool:
current_xy = np.array(current_config[:2], dtype=float)
goal_xy = np.array(goal_config[:2], dtype=float)
return float(np.linalg.norm(current_xy - goal_xy)) <= threshold
def run_planner_test(
planner_name: str,
robot_id: int,
movable_joints: list,
start_config: list,
goal_config: list,
ignored_ids: list,
timeout: float,
locked_indices: list = None,
suppress_output: bool = True,
cone_ids: Optional[list] = None,
world2d: Optional[Any] = None,
moving_obstacles: Optional[list] = None,
base_only_2d: bool = False,
) -> tuple[list | None, float, str]:
"""
Run a single planner and return (path, planning_time, error_msg).
"""
import pybullet as p
path = None
error_msg = ""
# For RRT-Connect and OMPL RRT* v2, we need to modify the goal to lock arm joints
# since they don't support locked_indices parameter
if planner_name in ["ompl_rrt_connect", "ompl_rrt_star_v2"] and locked_indices:
goal_config = list(goal_config)
for idx in locked_indices:
goal_config[idx] = start_config[idx]
start_time = time.time()
if base_only_2d:
import config
rng = np.random.default_rng(np.random.randint(0, 2**32 - 1))
start_xy = np.array(start_config[:2], dtype=float)
goal_xy = np.array(goal_config[:2], dtype=float)
if world2d is not None:
bounds = (
world2d.bounds.xmin,
world2d.bounds.xmax,
world2d.bounds.ymin,
world2d.bounds.ymax,
)
else:
xmin, xmax = config.MOBILE_BASE_BOUNDS
bounds = (xmin, xmax, xmin, xmax)
base_template = list(start_config)
def is_state_valid(xy: np.ndarray) -> bool:
base_template[0] = float(xy[0])
base_template[1] = float(xy[1])
for i, joint_idx in enumerate(movable_joints):
p.resetJointState(robot_id, joint_idx, base_template[i])
p.performCollisionDetection()
for body_id in range(p.getNumBodies()):
if body_id == robot_id or body_id in ignored_ids:
continue
if p.getClosestPoints(robot_id, body_id, config.COLLISION_MARGIN):
return False
return True
if planner_name == "custom_rrt_star_with_backup":
path, error_msg = _plan_rrt_star_2d(
start_xy,
goal_xy,
timeout,
rng,
bounds=bounds,
is_state_valid=is_state_valid,
)
if path is None:
path, error_msg = _plan_rrt_connect_2d(
start_xy,
goal_xy,
timeout,
rng,
bounds=bounds,
is_state_valid=is_state_valid,
)
elif planner_name in ["custom_rrt_star", "ompl_rrt_star", "ompl_rrt_star_v2"]:
path, error_msg = _plan_rrt_star_2d(
start_xy,
goal_xy,
timeout,
rng,
bounds=bounds,
is_state_valid=is_state_valid,
)
elif planner_name == "ompl_rrt_connect":
path, error_msg = _plan_rrt_connect_2d(
start_xy,
goal_xy,
timeout,
rng,
bounds=bounds,
is_state_valid=is_state_valid,
)
else:
path = None
error_msg = f"Unknown planner: {planner_name}"
for i, joint_idx in enumerate(movable_joints):
p.resetJointState(robot_id, joint_idx, start_config[i])
planning_time = time.time() - start_time
return path, planning_time, error_msg
try:
with SuppressOutput(suppress_output):
if planner_name == "custom_rrt_star":
# Pure RRT* - no fallback
from rrt_star import RRTStarPlanner
planner = RRTStarPlanner(
robot_id, movable_joints, ignored_ids=ignored_ids
)
path = planner.plan(
start_config,
goal_config,
timeout=timeout,
locked_indices=locked_indices,
)
elif planner_name == "custom_rrt_star_with_backup":
# RRT* with RRT-Connect fallback (as used in main.py)
from rrt_star import RRTStarPlanner
from RRT_connect import MobileManipulatorPlanner
# Try RRT* first
planner = RRTStarPlanner(
robot_id, movable_joints, ignored_ids=ignored_ids
)
path = planner.plan(
start_config,
goal_config,
timeout=timeout,
locked_indices=locked_indices,
)
# If RRT* fails, fall back to RRT-Connect
if path is None:
# Modify goal for RRT-Connect (doesn't support locked_indices)
backup_goal = list(goal_config)
if locked_indices:
for idx in locked_indices:
backup_goal[idx] = start_config[idx]
# Use cone_ids for backup planner (same as standalone RRT-Connect)
backup_ignored_ids = ignored_ids + (cone_ids or [])
backup_planner = MobileManipulatorPlanner(
robot_id,
movable_joints,
planner_type="RRTconnect",
ignored_ids=backup_ignored_ids,
)
path = backup_planner.plan(
start_config, backup_goal, timeout=timeout
)
elif planner_name == "ompl_rrt_star":
from planner import OMPLPlanner
planner = OMPLPlanner(robot_id, movable_joints, ignored_ids=ignored_ids)
path = planner.plan(
start_config,
goal_config,
timeout=timeout,
locked_indices=locked_indices,
)
elif planner_name == "ompl_rrt_connect":
from RRT_connect import MobileManipulatorPlanner
planner = MobileManipulatorPlanner(
robot_id,
movable_joints,
planner_type="RRTconnect",
ignored_ids=ignored_ids,
)
# RRT-Connect doesn't support locked_indices, goal was modified above
path = planner.plan(start_config, goal_config, timeout=timeout)
elif planner_name == "ompl_rrt_star_v2":
# Use the same wrapper as RRT-Connect for fairer comparison
from RRT_connect import MobileManipulatorPlanner
planner = MobileManipulatorPlanner(
robot_id,
movable_joints,
planner_type="RRTstar",
ignored_ids=ignored_ids,
)
path = planner.plan(start_config, goal_config, timeout=timeout)
else:
error_msg = f"Unknown planner: {planner_name}"
except Exception as e:
error_msg = str(e)
if not suppress_output:
traceback.print_exc()
planning_time = time.time() - start_time
return path, planning_time, error_msg
def setup_headless_environment(seed: int):
"""
Set up PyBullet environment in headless mode.
Uses the same functions as main.py for consistency.
Returns dict with robot_id, world2d, goal_config, movable_joints, ignored_ids, cone_ids.
"""
import pybullet as p
# Set seed before any random operations
random.seed(seed)
np.random.seed(seed)
# Import the working functions from scenario.py (same as main.py uses)
from scenario import (
create_environment,
find_plane_id,
generate_warehouse_layout,
build_warehouse_scene,
build_warehouse_logic,
spawn_moving_cones,
spawn_target_block_2,
)
from obstacles import Obstacle
import config
import inverse_kinematics as IK
# Use the same environment creation as main.py, but headless
env, robot_id = create_environment(render=False)
plane_id = find_plane_id()
# Get movable joints (same as main.py)
movable_joints = IK.get_movable_joints(robot_id, verbose=False)
# Generate warehouse (same as main.py)
layout = generate_warehouse_layout()
goal_pos_1, goal_shelf_id, goal_pos_2, goal_shelf_2_id, _ = build_warehouse_scene(
layout
)
target_block_id, target_block_pos = spawn_target_block_2(
goal_pos_1, collision=False
)
target_block_2_id, target_block_2_pos = spawn_target_block_2(
goal_pos_2, collision=False
)
# Build 2D world for obstacle checking
world2d = build_warehouse_logic(layout)
# Create moving obstacles (same as main.py)
moving_specs = [
{"radius": 0.2, "vx": 1.5},
{"radius": 0.25, "vx": 2},
{"radius": 0.2, "vx": 1.2},
]
corridor_rows = [
r
for r, row in enumerate(layout)
if 0 < r < len(layout) - 1 and "#" not in row and "G" not in row
]
if len(corridor_rows) < 3:
corridor_rows = [r for r in range(1, len(layout) - 1) if r % 2 == 0]
if not corridor_rows:
corridor_rows = [1, 3, 5]
if len(corridor_rows) >= 3:
chosen_rows = list(np.random.choice(corridor_rows, size=3, replace=False))
else:
chosen_rows = list(np.random.choice(corridor_rows, size=3, replace=True))
y_offset = -(len(layout) * config.CELL_SIZE) / 2
moving_obstacles = []
for row_idx, spec in zip(chosen_rows, moving_specs):
y = y_offset + row_idx * config.CELL_SIZE
radius = spec["radius"]
x0 = max(world2d.bounds.xmin + radius, world2d.bounds.xmin + config.CELL_SIZE)
moving_obstacles.append(
Obstacle(
center0=[x0, y],
velocity=[spec["vx"], 0.0],
radius=radius,
bounds=world2d.bounds,
)
)
cone_ids = spawn_moving_cones(moving_obstacles)
# Compute goal configuration using IK (same as main.py)
target_pos = target_block_pos
lock_x = target_pos[0]
lock_y = target_pos[1]
target_orn = p.getQuaternionFromEuler([np.pi / 2, 0, 0])
gripper_extent = 0.12
ik_result = IK.solve_ik(
robot_id=robot_id,
ee_id=12,
target_pos=target_pos,
target_orn=target_orn,
ik_indices=movable_joints,
base_lock={"mobile_joint_x": lock_x, "mobile_joint_y": lock_y},
base_lock_range=1.0,
gripper_offset=np.array([0, -gripper_extent, 0]),
)
joint_poses = list(ik_result["joint_poses"])
target_pos_2 = target_block_2_pos
lock_x_2 = target_pos_2[0]
lock_y_2 = target_pos_2[1]
ik_result_2 = IK.solve_ik(
robot_id=robot_id,
ee_id=12,
target_pos=target_pos_2,
target_orn=target_orn,
ik_indices=movable_joints,
base_lock={"mobile_joint_x": lock_x_2, "mobile_joint_y": lock_y_2},
base_lock_range=1.0,
gripper_offset=np.array([0, -gripper_extent, 0]),
)
joint_poses_2 = list(ik_result_2["joint_poses"])
# Create base goals (only base joints, arm at start position)
base_goal = [0] * len(movable_joints)
base_goal[0] = joint_poses[0]
base_goal[1] = joint_poses[1]
base_goal[2] = joint_poses[2]
base_goal_2 = [0] * len(movable_joints)
base_goal_2[0] = joint_poses_2[0]
base_goal_2[1] = joint_poses_2[1]
base_goal_2[2] = joint_poses_2[2]
# Start config is all zeros
start_config = [0] * len(movable_joints)
# Ignored IDs for collision checking (same as main.py)
ignored_ids = [plane_id] if plane_id != -1 else []
return {
"env": env,
"robot_id": robot_id,
"movable_joints": movable_joints,
"start_config": start_config,
"base_goal": base_goal,
"base_goal_2": base_goal_2,
"full_goal": joint_poses,
"full_goal_2": joint_poses_2,
"goal_pos_1": goal_pos_1,
"goal_pos_2": goal_pos_2,
"target_block_pos": target_block_pos,
"target_block_2_pos": target_block_2_pos,
"ignored_ids": ignored_ids,
"cone_ids": cone_ids,
"world2d": world2d,
"moving_obstacles": moving_obstacles,
"layout": layout,
}
def run_single_comparison(
run_id: int,
seed: int,
planners: list[str],
timeout: float,
skip_execution: bool = False,
verbose: bool = False,
output_dir: Path = None,
max_steps: int = 3000,
) -> list[PlannerRunResult]:
"""
Run all planners on the same scenario (same seed) with full multi-goal execution.
Phases (matching main.py):
1. Plan & execute base path to goal 1
2. Plan & execute arm to target, attach box
3. Plan & execute base path to goal 2
4. Plan & execute arm to target 2, detach box
Args:
run_id: Run identifier
max_steps: Max MPC steps per execution phase (default: 3000)
seed: Random seed for this scenario
planners: List of planner names to test
timeout: Planning timeout in seconds
skip_execution: If True, only test planning (no MPC)
verbose: If True, show verbose output from planners
output_dir: Directory for saving plots (optional)
Returns:
List of PlannerRunResult for each planner
"""
import pybullet as p
from Mpc_controller import HolonomicMPC, MPCParams, execute_mpc_path
from RRT_connect import (
KinematicGoalController,
KinematicPathController,
MobileManipulatorPlanner,
)
from simulation_monitor import SimulationMonitor
from obstacles import update_cone_positions
import inverse_kinematics as IK
results = []
print(f"\n{'=' * 60}")
print(f"Run {run_id} | Seed {seed}")
print(f"{'=' * 60}")
# Test each planner
for planner_name in planners:
print(f"\n Testing {planner_name}...")
result = PlannerRunResult(
planner_name=planner_name,
seed=seed,
run_id=run_id,
)
try:
env_data = setup_headless_environment(seed)
except Exception as e:
print(f"Failed to setup environment: {e}")
traceback.print_exc()
result.error_message = f"Environment setup failed: {e}"
results.append(result)
continue
env = env_data["env"]
robot_id = env_data["robot_id"]
movable_joints = env_data["movable_joints"]
start_config = env_data["start_config"]
base_goal = env_data["base_goal"]
base_goal_2 = env_data["base_goal_2"]
full_goal = env_data["full_goal"]
full_goal_2 = env_data["full_goal_2"]
target_block_pos = env_data["target_block_pos"]
target_block_2_pos = env_data["target_block_2_pos"]
goal_pos_1 = env_data["goal_pos_1"]
goal_pos_2 = env_data["goal_pos_2"]
ignored_ids = env_data["ignored_ids"]
cone_ids = env_data["cone_ids"]
world2d = env_data["world2d"]
moving_obstacles = env_data["moving_obstacles"]
layout = env_data["layout"]
arm_locked_indices = list(range(3, len(movable_joints)))
planner_ignored_ids = ignored_ids + cone_ids # All planners ignore cones
# MPC and controllers for execution
mpc = (
HolonomicMPC(MPCParams(dt=env.dt, horizon=40))
if not skip_execution
else None
)
arm_planner = MobileManipulatorPlanner(
robot_id, movable_joints, ignored_ids=planner_ignored_ids
)
arm_base_lock_indices = [0, 1, 2]
get_joint_pos = lambda: [
p.getJointState(robot_id, j)[0] for j in movable_joints
]
try:
# Reset robot to start config
for i, joint_idx in enumerate(movable_joints):
p.resetJointState(robot_id, joint_idx, start_config[i])
# Reset moving obstacle cones to initial positions (t=0)
update_cone_positions(cone_ids, moving_obstacles, t=0.0)
# Reset arm planner's carried object reference
arm_planner.set_carried_object(None)
total_planning_time = 0.0
total_path_length = 0.0
all_paths_2d = []
monitor = (
SimulationMonitor(safety_margin=0.1) if not skip_execution else None
)
if monitor:
monitor.start()
exec_start = time.time()
phase_failed = False
attached_box_id = None
path_3 = None # Initialize for phase 4 check
# ===== PHASE 1: Base path to goal 1 =====
print(f" Phase 1: Base path to goal 1...")
path, planning_time, error_msg = run_planner_test(
planner_name=planner_name,
robot_id=robot_id,
movable_joints=movable_joints,
start_config=start_config,
goal_config=base_goal,
ignored_ids=planner_ignored_ids,
timeout=timeout,
locked_indices=arm_locked_indices,
suppress_output=not verbose,
cone_ids=cone_ids,
world2d=world2d,
moving_obstacles=moving_obstacles,
base_only_2d=True,
)
total_planning_time += planning_time
result.phase_planning_time["base_path_1"] = planning_time
result.phase_success["base_path_1"] = path is not None
result.phase_path_length["base_path_1"] = (
compute_path_length(path) if path else 0.0
)
if path is None:
result.planning_success = False
result.error_message = f"Phase 1 failed: {error_msg}"
print(f" FAILED: {error_msg[:50] if error_msg else 'no path'}")
phase_failed = True
else: