Repository navigation
Expand file tree
/
Copy pathcontroller.py
More file actions
175 lines (146 loc) · 6.27 KB
/
Copy pathcontroller.py
File metadata and controls
175 lines (146 loc) · 6.27 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
import time
import numpy as np
import pybullet as p
import config
class KinematicController:
def __init__(self, env, robot_id, movable_joints, kp=config.CONTROLLER_KP):
self.env = env
self.robot_id = robot_id
self.movable_joints = movable_joints
self.kp = kp
self.max_vel = self._get_velocity_limits()
def _get_velocity_limits(self):
limits = []
for joint in self.movable_joints:
info = p.getJointInfo(self.robot_id, joint)
velocity_limit = info[11] if info[11] > 0 else config.DEFAULT_VELOCITY_LIMIT
limits.append(velocity_limit)
return np.array(limits)
def _get_current_config(self):
return np.array([p.getJointState(self.robot_id, j)[0] for j in self.movable_joints])
def _apply_velocity(self, velocity):
action = np.zeros(self.env.n())
action[:len(velocity)] = velocity
self.env.step(action)
def _snap_to_goal(self, goal_config, step_after=True):
for i, joint in enumerate(self.movable_joints):
p.resetJointState(self.robot_id, joint, goal_config[i])
if step_after:
self._apply_velocity(np.zeros(len(self.movable_joints)))
def snap_to_goal(self, goal_config, step_after=False):
"""Public helper to instantly set all joints to the supplied configuration.
step_after=False avoids a physics step that could cause large impulses
if the snapped configuration interpenetrates obstacles.
"""
self._snap_to_goal(goal_config, step_after=step_after)
def follow_arm_to_positions(
self,
goal_config,
arm_move_positions,
vel_limit=config.ARM_MAX_VEL,
accel_limit=config.ARM_MAX_ACCEL,
tol=config.FINAL_THRESHOLD,
timeout=config.CONTROLLER_TIMEOUT,
):
"""Move only the arm joints to the goal using a simple velocity/accel ramp.
- arm_move_positions: indices inside self.movable_joints that belong to the arm.
- Keeps base (other joints) fixed by not commanding them and by stepping with zero action.
"""
if not arm_move_positions:
return
dt = self.env.dt
arm_ids = [self.movable_joints[i] for i in arm_move_positions]
# Current and goal
q = self._get_current_config()
q_goal = np.array(goal_config)
v = np.zeros(len(arm_move_positions))
v_max = np.full(len(arm_move_positions), vel_limit)
a_max = np.full(len(arm_move_positions), accel_limit)
start_time = time.time()
while True:
# Per-joint ramp respecting accel and stopping distance
done = True
for k, pos_idx in enumerate(arm_move_positions):
err = float(q_goal[pos_idx] - q[pos_idx])
if abs(err) > tol:
done = False
sgn = 1.0 if err >= 0.0 else -1.0
# Accelerate/decelerate with cap
v_des = v[k] + sgn * a_max[k] * dt
v_des = max(-v_max[k], min(v_des, v_max[k]))
# Ensure we can stop within remaining distance
v_stop = (2.0 * a_max[k] * abs(err)) ** 0.5
v_des = sgn * min(abs(v_des), v_stop)
# Integrate
q[pos_idx] += v_des * dt
v[k] = v_des
# Apply only arm joints via reset; step physics with zero action
for k, pos_idx in enumerate(arm_move_positions):
p.resetJointState(self.robot_id, arm_ids[k], q[pos_idx])
# advance time without commanding env actions
self.env.step(np.zeros(self.env.n()))
if done:
break
if time.time() - start_time > timeout:
print("Controller: Arm move timeout.")
break
def follow_path(
self,
path,
lookahead_dist=config.LOOKAHEAD_DISTANCE,
final_threshold=config.FINAL_THRESHOLD,
accel_limits=None,
vel_limits=None,
controlled_indices=None,
):
print(f"Controller: Following path with {len(path)} waypoints...")
current_idx = 0
max_idx = len(path) - 1
start_time = time.time()
stall_count = 0
# Optional per-joint limits and control mask
n = len(self.movable_joints)
lim_vel = np.array(vel_limits) if vel_limits is not None else self.max_vel
lim_vel = np.resize(lim_vel, n)
lim_acc = np.array(accel_limits) if accel_limits is not None else None
if lim_acc is not None:
lim_acc = np.resize(lim_acc, n)
mask = np.ones(n)
if controlled_indices is not None:
mask[:] = 0.0
for i in controlled_indices:
if 0 <= i < n:
mask[i] = 1.0
prev_vel = np.zeros(n)
while True:
current_q = self._get_current_config()
target_q = np.array(path[current_idx])
err = (target_q - current_q) * mask
dist_to_target = np.linalg.norm(err)
if current_idx < max_idx and dist_to_target < lookahead_dist:
current_idx += 1
target_q = np.array(path[current_idx])
if current_idx == max_idx and dist_to_target < final_threshold:
self._snap_to_goal(path[max_idx])
break
desired = np.clip(err * self.kp, -lim_vel, lim_vel)
if lim_acc is not None:
max_dv = lim_acc * config.SIMULATION_DT
dv = desired - prev_vel
dv = np.clip(dv, -max_dv, max_dv)
velocity = prev_vel + dv
prev_vel = velocity
else:
velocity = desired
self._apply_velocity(velocity)
if current_idx == max_idx and np.linalg.norm(velocity) < config.STALL_VELOCITY_THRESHOLD:
stall_count += 1
if stall_count >= config.STALL_ITERATIONS:
print(f"Controller: Converged (stalled at dist={dist_to_target:.4f})")
self._snap_to_goal(path[max_idx])
break
else:
stall_count = 0
if time.time() - start_time > config.CONTROLLER_TIMEOUT:
print("Controller: Timeout reached!")
break