Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
465 lines (394 loc) · 14.3 KB
/
Copy pathmain.py
File metadata and controls
465 lines (394 loc) · 14.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
import argparse
import numpy as np
import pybullet as p
from Mpc_controller import HolonomicMPC, MPCParams, execute_mpc_path
import time
import inverse_kinematics as IK
from rrt_star import RRTStarPlanner
import config
from obstacles import Obstacle
from scenario import (
build_warehouse_scene,
spawn_moving_cones,
generate_warehouse_layout,
build_warehouse_logic,
create_environment,
find_plane_id,
spawn_target_block_2,
)
from robot_def import verify_base_position
from RRT_connect import (
KinematicGoalController,
KinematicPathController,
MobileManipulatorPlanner,
)
def run_planning_demo(seed=None, follow_camera=False):
"""Run the mobile manipulator planning demo."""
if seed is not None:
np.random.seed(seed)
# Build environment and robot
env, robot_id = create_environment()
plane_id = find_plane_id()
if follow_camera:
p.resetDebugVisualizerCamera(
cameraDistance=15.0,
cameraYaw=0,
cameraPitch=-60,
cameraTargetPosition=[0, 0, 0],
)
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
)
world2d = build_warehouse_logic(layout)
# Moving obstacles
moving_specs = [
{"radius": 0.2, "vx": 1.5},
{"radius": 0.25, "vx": 2},
{"radius": 0.2, "vx": 1.2},
]
def is_spawn_free(world2d, x, y, radius):
if x < world2d.bounds.xmin + radius or x > world2d.bounds.xmax - radius:
return False
if y < world2d.bounds.ymin + radius or y > world2d.bounds.ymax - radius:
return False
for obs in world2d.obstacles:
if obs.signed_distance([x, y], inflate=radius) <= 0.0:
return False
return True
def find_free_spawn_x(world2d, y, radius, x_start=None, step=None):
if x_start is None:
x_start = world2d.bounds.xmin + radius
if step is None:
step = max(0.1, min(0.5, config.CELL_SIZE * 0.5))
x = float(x_start)
while x <= world2d.bounds.xmax - radius:
if is_spawn_free(world2d, x, y, radius):
return x
x += step
raise ValueError(f"No free spawn slot at y={y} for radius={radius}")
# 1. Group empty rows into 2-wide corridor units
all_empty = [
r
for r, row in enumerate(layout)
if 0 < r < len(layout) - 1
and "#" not in row
and "G" not in row
and "2" not in row
]
corridors = []
i = 0
while i < len(all_empty) - 1:
if all_empty[i + 1] == all_empty[i] + 1:
# Store the STARTING row index of the corridor
corridors.append(all_empty[i])
i += 2
else:
i += 1
# 2. Pick 3 unique corridors (if available)
if len(corridors) >= 3:
chosen_corridor_starts = list(
np.random.choice(corridors, size=3, replace=False)
)
else:
chosen_corridor_starts = list(np.random.choice(corridors, size=3, replace=True))
# 3. Calculate the Y position exactly in the middle
y_offset = -(len(layout) * config.CELL_SIZE) / 2
moving_obstacles = []
for start_idx, spec in zip(chosen_corridor_starts, moving_specs):
# Adding 0.5 to the index puts the coordinate on the line between rows
center_row_f = start_idx + 0.5
y = y_offset + (center_row_f * config.CELL_SIZE)
radius = spec["radius"]
x0 = max(world2d.bounds.xmin + radius, world2d.bounds.xmin + config.CELL_SIZE)
# Check for collisions at this centered Y position
if not is_spawn_free(world2d, x0, y, radius):
try:
x0 = find_free_spawn_x(world2d, y, radius)
except ValueError:
continue
moving_obstacles.append(
Obstacle(
center0=[x0, y],
velocity=[spec["vx"], 0.0],
radius=radius,
bounds=world2d.bounds,
)
)
cone_ids = spawn_moving_cones(moving_obstacles)
# MPC setup
dt = env.dt
mpc = HolonomicMPC(MPCParams(dt=dt, horizon=40))
# IK setup
target_pos = target_block_pos
lock_x, lock_y = target_pos[0], target_pos[1]
target_orn = p.getQuaternionFromEuler([np.pi / 2, 0, 0])
ik_indices = IK.get_movable_joints(robot_id, verbose=True)
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=ik_indices,
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"])
print(
"Joint positions x, y, theta:", joint_poses[0], joint_poses[1], joint_poses[2]
)
# Reset joints
for joint_idx in ik_indices:
p.resetJointState(robot_id, joint_idx, 0.0)
p.addUserDebugLine(
[joint_poses[0], joint_poses[1], 0.0],
[joint_poses[0], joint_poses[1], 2.0],
[1, 0, 0],
4,
0,
)
# Planners - ignore cones since MPC handles dynamic obstacles
ignored_ids = [plane_id] if plane_id != -1 else []
ignored_ids += cone_ids
rrt_star_planner = RRTStarPlanner(robot_id, ik_indices, ignored_ids=ignored_ids)
connect_planner = MobileManipulatorPlanner(
robot_id, ik_indices, ignored_ids=ignored_ids
)
base_goal = [0] * len(ik_indices)
base_goal[0], base_goal[1], base_goal[2] = (
joint_poses[0],
joint_poses[1],
joint_poses[2],
)
start_config = [0] * len(ik_indices)
arm_locked_indices = list(range(3, len(ik_indices)))
# Phase 1: Plan base path
base_path = rrt_star_planner.plan(
start_config, base_goal, locked_indices=arm_locked_indices
)
if not base_path:
print("RRT* failed, trying RRT-Connect...")
base_path = connect_planner.plan(start_config, base_goal)
if not base_path:
raise RuntimeError("Base path planning failed!")
print("Executing base path...")
base_path_2d = [np.array([q[0], q[1]], dtype=float) for q in base_path]
sim_time = 0.0
sim_time = execute_mpc_path(
env,
robot_id,
mpc,
world2d,
base_path_2d,
moving_obstacles,
cone_ids,
t0=sim_time,
follow_camera=follow_camera,
)
verify_base_position(robot_id, base_goal)
print("Base at goal!")
# Fine positioning
goal_controller = KinematicGoalController(env, robot_id, ik_indices, kp=5.0)
goal_controller.go_to_pose(base_goal)
# Phase 2: Arm to target
print("Planning arm path...")
get_joint_pos = lambda: [p.getJointState(robot_id, j)[0] for j in ik_indices]
actual = get_joint_pos()
start_config = [0.0] * len(ik_indices)
start_config[0], start_config[1], start_config[2] = actual[0], actual[1], actual[2]
arm_path = connect_planner.plan(start_config, joint_poses)
path_controller = KinematicPathController(env, robot_id, ik_indices, kp=5.0)
path_controller.follow_path(arm_path)
print("Arm at target!")
# Attach box
attached_box_id = IK.attach_kinematic_box(robot_id, 12)
connect_planner.set_carried_object(attached_box_id)
rrt_star_planner.ignored_ids.append(attached_box_id)
# Return arm
path_2 = connect_planner.plan(get_joint_pos(), start_config)
path_controller.follow_path(path_2)
# Phase 3: Move to second goal
goal_vec = np.array(goal_pos_2) - np.array(goal_pos_1)
base_goal_2 = [0] * len(ik_indices)
base_goal_2[0] = base_goal[0] + goal_vec[0]
base_goal_2[1] = base_goal[1] + goal_vec[1]
base_goal_2[2] = base_goal[2] + goal_vec[2]
p.resetJointState(robot_id, 13, 0.01)
p.resetJointState(robot_id, 14, 0.01)
path_3 = rrt_star_planner.plan(
get_joint_pos(), base_goal_2, locked_indices=arm_locked_indices
)
if not path_3:
print("RRT* failed, trying RRT-Connect...")
path_3 = connect_planner.plan(get_joint_pos(), base_goal_2)
if not path_3:
raise RuntimeError("Second base path planning failed!")
path_3_2d = [np.array([q[0], q[1]], dtype=float) for q in path_3]
sim_time = execute_mpc_path(
env,
robot_id,
mpc,
world2d,
path_3_2d,
moving_obstacles,
cone_ids,
t0=sim_time,
follow_camera=follow_camera,
)
print("Kinematic goal controller taking over...")
goal_controller.go_to_pose(base_goal_2)
# Phase 4: Arm to second target
joint_poses[0] += goal_vec[0]
joint_poses[1] += goal_vec[1]
joint_poses[2] += goal_vec[2]
p.resetJointState(robot_id, 13, 0.01)
p.resetJointState(robot_id, 14, 0.01)
path_4 = connect_planner.plan(get_joint_pos(), joint_poses)
path_controller.follow_path(path_4)
# Cleanup
connect_planner.set_carried_object(None)
p.removeBody(attached_box_id)
print("Demo complete!")
# Keep simulation running
while True:
p.stepSimulation()
time.sleep(config.SIMULATION_DT)
def run_benchmark(seed=None, record_video=False, follow_camera=False):
"""Run demo with benchmarking enabled."""
from benchmark import BenchmarkRecorder
from benchmark_plots import generate_all_plots
if seed is not None:
np.random.seed(seed)
recorder = BenchmarkRecorder(random_seed=seed)
recorder.start_log_capture()
recorder.start_phase("total_execution")
env, robot_id = create_environment()
plane_id = find_plane_id()
if record_video:
recorder.start_video_recording()
p.resetDebugVisualizerCamera(
cameraDistance=15.0,
cameraYaw=0,
cameraPitch=-60,
cameraTargetPosition=[0, 0, 0],
)
layout = generate_warehouse_layout()
goal_pos_1, _, goal_pos_2, _, _ = build_warehouse_scene(layout)
spawn_target_block_2(goal_pos_1, collision=False)
spawn_target_block_2(goal_pos_2, collision=False)
recorder.set_layout(layout)
recorder.set_goal_positions([goal_pos_1, goal_pos_2])
world2d = build_warehouse_logic(layout)
# Moving obstacles (same setup as run_planning_demo)
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]
chosen_rows = list(
np.random.choice(corridor_rows, size=3, replace=len(corridor_rows) < 3)
)
y_offset = -(len(layout) * config.CELL_SIZE) / 2
moving_obstacles = []
for row_idx, spec in zip(chosen_rows, moving_specs, strict=True):
y = y_offset + row_idx * config.CELL_SIZE
moving_obstacles.append(
Obstacle(
center0=[world2d.bounds.xmin + config.CELL_SIZE, y],
velocity=[spec["vx"], 0.0],
radius=spec["radius"],
bounds=world2d.bounds,
)
)
cone_ids = spawn_moving_cones(moving_obstacles)
mpc = HolonomicMPC(MPCParams(dt=env.dt, horizon=40))
ik_indices = IK.get_movable_joints(robot_id, verbose=False)
target_pos = [goal_pos_1[0], goal_pos_1[1], 0.5]
ik_result = IK.solve_ik(
robot_id=robot_id,
ee_id=12,
target_pos=target_pos,
target_orn=p.getQuaternionFromEuler([np.pi / 2, 0, 0]),
ik_indices=ik_indices,
base_lock={"mobile_joint_x": target_pos[0], "mobile_joint_y": target_pos[1]},
base_lock_range=1.0,
gripper_offset=np.array([0, -0.12, 0]),
)
joint_poses = list(ik_result["joint_poses"])
for j in ik_indices:
p.resetJointState(robot_id, j, 0.0)
ignored_ids = [plane_id] if plane_id != -1 else []
ignored_ids += cone_ids # MPC handles dynamic obstacles
rrt_star = RRTStarPlanner(robot_id, ik_indices, ignored_ids=ignored_ids)
connect = MobileManipulatorPlanner(robot_id, ik_indices, ignored_ids=ignored_ids)
base_goal = [0] * len(ik_indices)
base_goal[0], base_goal[1], base_goal[2] = (
joint_poses[0],
joint_poses[1],
joint_poses[2],
)
arm_locked = list(range(3, len(ik_indices)))
# Plan and execute
recorder.start_phase("planning_1")
t0 = time.time()
path = rrt_star.plan([0] * len(ik_indices), base_goal, locked_indices=arm_locked)
if not path:
path = connect.plan([0] * len(ik_indices), base_goal)
recorder.end_phase("planning_1")
recorder.record_planning_result(
"base_1", "rrt", path is not None, time.time() - t0, path
)
if not path:
raise RuntimeError("Planning failed")
path_2d = [np.array([q[0], q[1]]) for q in path]
execute_mpc_path(
env,
robot_id,
mpc,
world2d,
path_2d,
moving_obstacles,
cone_ids,
recorder=recorder,
follow_camera=follow_camera,
)
recorder.mark_goal_reached(0)
recorder.end_phase("total_execution")
recorder.stop_recording()
result = recorder.finalize(task_success=True)
recorder.save_results()
generate_all_plots(result, str(recorder.output_dir / "plots"), world2d, [path_2d])
print(f"\nResults saved to: {recorder.output_dir}")
recorder.stop_log_capture()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Mobile Manipulator Planning Demo")
parser.add_argument("--benchmark", action="store_true", help="Enable benchmarking")
parser.add_argument("--record-video", action="store_true", help="Record video")
parser.add_argument("--seed", type=int, default=None, help="Random seed")
parser.add_argument(
"--follow-camera", action="store_true", help="Camera follows robot"
)
args = parser.parse_args()
if args.benchmark:
run_benchmark(
seed=args.seed,
record_video=args.record_video,
follow_camera=args.follow_camera,
)
else:
run_planning_demo(seed=args.seed, follow_camera=args.follow_camera)