Repository navigation
Expand file tree
/
Copy pathRRT_connect.py
More file actions
374 lines (307 loc) · 12.8 KB
/
Copy pathRRT_connect.py
File metadata and controls
374 lines (307 loc) · 12.8 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
# =============================================================================
# 1. OMPL PLANNER CLASS
# =============================================================================
import pybullet as p
import numpy as np
import time
import ompl.base as ob
try:
from ompl import base as ob
from ompl import geometric as og
except ImportError:
print("CRITICAL: OMPL not found. Please install ompl bindings.")
exit()
class MobileManipulatorPlanner:
def __init__(
self,
robot_id,
movable_joints,
planner_type="RRTconnect",
planner_range=0.1,
ignored_ids=None,
):
self.robot_id = robot_id
self.joints = movable_joints
self.ndof = len(movable_joints)
self.ignored_ids = ignored_ids if ignored_ids is not None else []
self.planner_type = planner_type
self.planner_range = planner_range
# Create State Space (Simply R^N)
self.space = ob.RealVectorStateSpace(self.ndof)
bounds = ob.RealVectorBounds(self.ndof)
min_x, max_x = (-12, 12)
min_y, max_y = (-12, 12)
self.carried_obj_id = None # Add this
print("\n=== OMPL JOINT BOUNDS DEBUG ===")
lower_bounds = []
upper_bounds = []
for i, j_idx in enumerate(self.joints):
info = p.getJointInfo(robot_id, j_idx)
j_name = info[1].decode("utf-8")
lower, upper = info[8], info[9]
# 1. Mobile Base Logic (Override with Scene Bounds)
if "mobile_joint_x" in j_name or ("x" in j_name and "base" in j_name):
lower, upper = min_x, max_x
elif "mobile_joint_y" in j_name or ("y" in j_name and "base" in j_name):
lower, upper = min_y, max_y
# We assume these are continuous joints or simply uncapped.
if lower >= upper:
lower, upper = -6.28, 6.28
elif abs(upper - lower) < 1e-5:
upper += 0.01
bounds.setLow(i, lower)
bounds.setHigh(i, upper)
lower_bounds.append(lower)
upper_bounds.append(upper)
print(f"J{i} [{j_name}]: {lower:.3f} to {upper:.3f}")
print("===============================\n")
self.lower_bounds = np.array(lower_bounds, dtype=float)
self.upper_bounds = np.array(upper_bounds, dtype=float)
self.space.setBounds(bounds)
self.si = ob.SpaceInformation(self.space)
self.si.setStateValidityChecker(ob.StateValidityCheckerFn(self.is_state_valid))
self.si.setup()
def set_carried_object(self, obj_id):
self.carried_obj_id = obj_id
def is_state_valid(self, state):
# 1. Teleport Robot joints to the candidate state
for i, j_idx in enumerate(self.joints):
p.resetJointState(self.robot_id, j_idx, state[i])
# 2. Update Carried Object Position
if self.carried_obj_id is not None:
# We must use the same offset used in attach_kinematic_box
finger_offset = [0.0, 0.0, 0.12]
ee_state = p.getLinkState(self.robot_id, 12, computeForwardKinematics=True)
ee_pos = ee_state[4]
ee_orn = ee_state[5]
# Convert local offset to world position based on current EE orientation
offset_world, _ = p.multiplyTransforms(
[0, 0, 0], ee_orn, finger_offset, [0, 0, 0, 1]
)
box_pos_world = np.array(ee_pos) + np.array(offset_world)
# Teleport the box to where it would be in this configuration
p.resetBasePositionAndOrientation(
self.carried_obj_id, box_pos_world, ee_orn
)
# 3. Perform Collision Check
p.performCollisionDetection()
# Check Robot
if self._has_collision(self.robot_id):
return False
# Check Box
if self.carried_obj_id is not None:
if self._has_collision(self.carried_obj_id):
return False
return True
def _has_collision(self, body_id):
contact_points = p.getContactPoints(body_id)
for point in contact_points:
# point[1] is Body A, point[2] is Body B
body_a = point[1]
body_b = point[2]
# Determine which body is the "obstacle"
other_body = body_b if body_a == body_id else body_a
# Ignore collisions with itself or its carrier/carried object
if other_body == self.robot_id or other_body == self.carried_obj_id:
continue
# Ignore ground or specific targets
if other_body not in self.ignored_ids:
return True
return False
def plan(
self,
start_conf,
goal_conf,
timeout=10.0,
locked_indices=None,
locked_values=None,
):
# 1. Create Start/Goal
start = ob.State(self.space)
goal = ob.State(self.space)
for i in range(self.ndof):
start[i] = start_conf[i]
goal[i] = goal_conf[i]
# Optionally lock joints (e.g., base) by tightening bounds
if locked_indices:
if locked_values is None:
locked_values = [start_conf[i] for i in locked_indices]
for idx, value in zip(locked_indices, locked_values):
start[idx] = value
goal[idx] = value
temp_bounds = ob.RealVectorBounds(self.ndof)
for i in range(self.ndof):
temp_bounds.setLow(i, self.lower_bounds[i])
temp_bounds.setHigh(i, self.upper_bounds[i])
for idx, value in zip(locked_indices, locked_values):
temp_bounds.setLow(idx, value)
temp_bounds.setHigh(idx, value)
self.space.setBounds(temp_bounds)
self.space.setup()
self.si.setup()
# 2. Define Problem
pdef = ob.ProblemDefinition(self.si)
pdef.setStartAndGoalStates(start, goal)
# 3. Create Planner (RRT*)
if self.planner_type == "RRTstar":
planner = og.RRTstar(self.si)
else:
planner = og.RRTConnect(self.si)
planner.setRange(self.planner_range)
planner.setProblemDefinition(pdef)
planner.setup()
# 4. Solve
# IMPORTANT: We save physics state because collision checking moves the robot
p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 0)
state_id = p.saveState()
print("OMPL: Planning...")
try:
solved = planner.solve(timeout)
finally:
if locked_indices:
restore_bounds = ob.RealVectorBounds(self.ndof)
for i in range(self.ndof):
restore_bounds.setLow(i, self.lower_bounds[i])
restore_bounds.setHigh(i, self.upper_bounds[i])
self.space.setBounds(restore_bounds)
self.space.setup()
self.si.setup()
p.restoreState(state_id) # Put robot back where it was
p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1)
if solved:
print("OMPL: Path Found!")
path = pdef.getSolutionPath()
path.interpolate(200) # Resample for smooth execution
# Convert to list of python lists
path_states = []
for i in range(path.getStateCount()):
st = path.getState(i)
path_states.append([st[j] for j in range(self.ndof)])
return path_states
else:
print("OMPL: No Path Found.")
return None
# =============================================================================
# 2. KINEMATIC PATH CONTROLLER
# =============================================================================
class KinematicPathController:
def __init__(self, env, robot_id, movable_joints, kp=10.0):
self.env = env
self.robot_id = robot_id
self.movable_joints = movable_joints
self.kp = kp
# Retrieve velocity limits
self.max_vel = []
for j in movable_joints:
info = p.getJointInfo(robot_id, j)
v_limit = info[11]
if v_limit <= 0:
v_limit = 5.0
self.max_vel.append(v_limit)
self.max_vel = np.array(self.max_vel)
def follow_path(self, path, lookahead_dist=0.3, final_threshold=0.05):
"""
Smoothly follows the path using a lookahead logic.
"""
if path is None or len(path) == 0:
print("Controller: No path to follow (planner returned None/empty).")
return
print(f"Controller: Following path with {len(path)} waypoints...")
current_idx = 0
max_idx = len(path) - 1
# Safety timeout
start_time = time.time()
timeout = 180.0
while True:
# 1. Get Current Joint Config
current_q = []
for j in self.movable_joints:
state = p.getJointState(self.robot_id, j)[0]
current_q.append(state)
current_q = np.array(current_q)
# 2. Determine Current Target
# If we are close enough to the current target, switch to the next one
# UNLESS we are at the very last waypoint.
target_q = np.array(path[current_idx])
dist_to_target = np.linalg.norm(target_q - current_q)
if current_idx < max_idx and dist_to_target < lookahead_dist:
current_idx += 1
# Don't step simulation here, just update target immediately for smoothness
target_q = np.array(path[current_idx])
# 3. Check if Final Goal Reached
if current_idx == max_idx and dist_to_target < final_threshold:
# Stop the robot
self.env.step(np.zeros(self.env.n()))
break
# 4. Calculate Velocity (P-Control)
error = target_q - current_q
vel = error * self.kp
# 5. Clip Limits
vel = np.clip(vel, -self.max_vel, self.max_vel)
# 6. Apply Action
action = np.zeros(self.env.n())
for k in range(min(len(vel), len(action))):
action[k] = vel[k]
self.env.step(action)
# 7. Timeout Break
if time.time() - start_time > timeout:
print("Controller: Timeout reached!")
break
# =============================================================================
# 3. KINEMATIC GOAL CONTROLLER
# =============================================================================
class KinematicGoalController:
def __init__(self, env, robot_id, movable_joints, kp=5.0):
self.env = env
self.robot_id = robot_id
self.movable_joints = movable_joints
self.kp = kp
# Retrieve velocity limits from PyBullet
self.max_vel = []
for j in movable_joints:
info = p.getJointInfo(robot_id, j)
v_limit = info[11]
if v_limit <= 0:
v_limit = 5.0
self.max_vel.append(v_limit)
self.max_vel = np.array(self.max_vel)
def go_to_pose(self, target_q, threshold=0.02, timeout=60.0, max_accel=0.05):
"""
Moves the robot directly to a single target joint configuration.
"""
target_q = np.array(target_q)
start_time = time.time()
prev_vel = np.zeros(len(self.movable_joints))
print(f"Controller: Moving to target configuration...")
while True:
# 1. Get Current Joint Config
current_q = np.array(
[p.getJointState(self.robot_id, j)[0] for j in self.movable_joints]
)
# 2. Calculate Distance to Goal
error = target_q - current_q
dist_to_goal = np.linalg.norm(error)
# 3. Check Stop Condition
if dist_to_goal < threshold:
self.env.step(np.zeros(self.env.n()))
print("Controller: Destination reached.")
break
# 4. P-Control for Velocity
desired_vel = error * self.kp
# 5. Smooth the start (Acceleration Limiting)
# This prevents the "teleportation" jerk
vel_diff = desired_vel - prev_vel
vel_diff = np.clip(vel_diff, -max_accel, max_accel)
applied_vel = prev_vel + vel_diff
# 6. Clip to Max Velocity
applied_vel = np.clip(applied_vel, -self.max_vel, self.max_vel)
prev_vel = applied_vel
# 7. Apply Action
action = np.zeros(self.env.n())
for k in range(min(len(applied_vel), len(action))):
action[k] = applied_vel[k]
self.env.step(action)
# 8. Safety Timeout
if time.time() - start_time > timeout:
print("Controller: Timeout reached before hitting goal.")
break