nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
pi_2_pi
(angle)
return angle
98
105
def pi_2_pi(angle): while(angle > math.pi): angle = angle - 2.0 * math.pi while(angle < -math.pi): angle = angle + 2.0 * math.pi return angle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L98-L105
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
92.307692
8
3
100
0
def pi_2_pi(angle): while(angle > math.pi): angle = angle - 2.0 * math.pi while(angle < -math.pi): angle = angle + 2.0 * math.pi return angle
661
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
rear_wheel_feedback_control
(state, e, k, yaw_ref)
return delta
107
119
def rear_wheel_feedback_control(state, e, k, yaw_ref): v = state.v th_e = pi_2_pi(state.yaw - yaw_ref) omega = v * k * math.cos(th_e) / (1.0 - k * e) - \ KTH * abs(v) * th_e - KE * v * math.sin(th_e) * e / th_e if th_e == 0.0 or omega == 0.0: return 0.0 delta = math.atan2(L * omega / v, 1.0) return delta
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L107-L119
2
[ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12 ]
92.307692
[]
0
false
92.307692
13
3
100
0
def rear_wheel_feedback_control(state, e, k, yaw_ref): v = state.v th_e = pi_2_pi(state.yaw - yaw_ref) omega = v * k * math.cos(th_e) / (1.0 - k * e) - \ KTH * abs(v) * th_e - KE * v * math.sin(th_e) * e / th_e if th_e == 0.0 or omega == 0.0: return 0.0 delta = math.atan2(L * omega / v, 1.0) return delta
662
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
simulate
(path_ref, goal)
return t, x, y, yaw, v, goal_flag
122
176
def simulate(path_ref, goal): T = 500.0 # max simulation time goal_dis = 0.3 state = State(x=-0.0, y=-0.0, yaw=0.0, v=0.0) time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] goal_flag = False s = np.arange(0, path_ref.length, 0.1) e, k, yaw_ref, s0 = path_ref.calc_track_error(state.x, state.y, 0.0) while T >= time: e, k, yaw_ref, s0 = path_ref.calc_track_error(state.x, state.y, s0) di = rear_wheel_feedback_control(state, e, k, yaw_ref) speed_ref = calc_target_speed(state, yaw_ref) ai = pid_control(speed_ref, state.v) state.update(ai, di, dt) time = time + dt # check goal dx = state.x - goal[0] dy = state.y - goal[1] if math.hypot(dx, dy) <= goal_dis: print("Goal") goal_flag = True break x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) if show_animation: plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(path_ref.X(s), path_ref.Y(s), "-r", label="course") plt.plot(x, y, "ob", label="trajectory") plt.plot(path_ref.X(s0), path_ref.Y(s0), "xg", label="target") plt.axis("equal") plt.grid(True) plt.title("speed[km/h]:{:.2f}, target s-param:{:.2f}".format(round(state.v * 3.6, 2), s0)) plt.pause(0.0001) return t, x, y, yaw, v, goal_flag
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L122-L176
2
[ 0, 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, 53, 54 ]
80
[ 42, 44, 46, 47, 48, 49, 50, 51, 52 ]
16.363636
false
92.307692
55
4
83.636364
0
def simulate(path_ref, goal): T = 500.0 # max simulation time goal_dis = 0.3 state = State(x=-0.0, y=-0.0, yaw=0.0, v=0.0) time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] goal_flag = False s = np.arange(0, path_ref.length, 0.1) e, k, yaw_ref, s0 = path_ref.calc_track_error(state.x, state.y, 0.0) while T >= time: e, k, yaw_ref, s0 = path_ref.calc_track_error(state.x, state.y, s0) di = rear_wheel_feedback_control(state, e, k, yaw_ref) speed_ref = calc_target_speed(state, yaw_ref) ai = pid_control(speed_ref, state.v) state.update(ai, di, dt) time = time + dt # check goal dx = state.x - goal[0] dy = state.y - goal[1] if math.hypot(dx, dy) <= goal_dis: print("Goal") goal_flag = True break x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) if show_animation: plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(path_ref.X(s), path_ref.Y(s), "-r", label="course") plt.plot(x, y, "ob", label="trajectory") plt.plot(path_ref.X(s0), path_ref.Y(s0), "xg", label="target") plt.axis("equal") plt.grid(True) plt.title("speed[km/h]:{:.2f}, target s-param:{:.2f}".format(round(state.v * 3.6, 2), s0)) plt.pause(0.0001) return t, x, y, yaw, v, goal_flag
663
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
calc_target_speed
(state, yaw_ref)
return target_speed
178
191
def calc_target_speed(state, yaw_ref): target_speed = 10.0 / 3.6 dyaw = yaw_ref - state.yaw switch = math.pi / 4.0 <= dyaw < math.pi / 2.0 if switch: state.direction *= -1 return 0.0 if state.direction != 1: return -target_speed return target_speed
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L178-L191
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13 ]
92.857143
[ 11 ]
7.142857
false
92.307692
14
3
92.857143
0
def calc_target_speed(state, yaw_ref): target_speed = 10.0 / 3.6 dyaw = yaw_ref - state.yaw switch = math.pi / 4.0 <= dyaw < math.pi / 2.0 if switch: state.direction *= -1 return 0.0 if state.direction != 1: return -target_speed return target_speed
664
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
main
()
193
233
def main(): print("rear wheel feedback tracking start!!") ax = [0.0, 6.0, 12.5, 5.0, 7.5, 3.0, -1.0] ay = [0.0, 0.0, 5.0, 6.5, 3.0, 5.0, -2.0] goal = [ax[-1], ay[-1]] reference_path = CubicSplinePath(ax, ay) s = np.arange(0, reference_path.length, 0.1) t, x, y, yaw, v, goal_flag = simulate(reference_path, goal) # Test assert goal_flag, "Cannot goal" if show_animation: # pragma: no cover plt.close() plt.subplots(1) plt.plot(ax, ay, "xb", label="input") plt.plot(reference_path.X(s), reference_path.Y(s), "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots(1) plt.plot(s, np.rad2deg(reference_path.calc_yaw(s)), "-r", label="yaw") plt.grid(True) plt.legend() plt.xlabel("line length[m]") plt.ylabel("yaw angle[deg]") plt.subplots(1) plt.plot(s, reference_path.calc_curvature(s), "-r", label="curvature") plt.grid(True) plt.legend() plt.xlabel("line length[m]") plt.ylabel("curvature [1/m]") plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L193-L233
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
82.352941
[]
0
false
92.307692
41
3
100
0
def main(): print("rear wheel feedback tracking start!!") ax = [0.0, 6.0, 12.5, 5.0, 7.5, 3.0, -1.0] ay = [0.0, 0.0, 5.0, 6.5, 3.0, 5.0, -2.0] goal = [ax[-1], ay[-1]] reference_path = CubicSplinePath(ax, ay) s = np.arange(0, reference_path.length, 0.1) t, x, y, yaw, v, goal_flag = simulate(reference_path, goal) # Test assert goal_flag, "Cannot goal" if show_animation: # pragma: no cover plt.close() plt.subplots(1) plt.plot(ax, ay, "xb", label="input") plt.plot(reference_path.X(s), reference_path.Y(s), "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots(1) plt.plot(s, np.rad2deg(reference_path.calc_yaw(s)), "-r", label="yaw") plt.grid(True) plt.legend() plt.xlabel("line length[m]") plt.ylabel("yaw angle[deg]") plt.subplots(1) plt.plot(s, reference_path.calc_curvature(s), "-r", label="curvature") plt.grid(True) plt.legend() plt.xlabel("line length[m]") plt.ylabel("curvature [1/m]") plt.show()
665
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0, direction=1)
26
31
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0, direction=1): self.x = x self.y = y self.yaw = yaw self.v = v self.direction = direction
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L26-L31
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
92.307692
6
1
100
0
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0, direction=1): self.x = x self.y = y self.yaw = yaw self.v = v self.direction = direction
666
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
State.update
(self, a, delta, dt)
33
37
def update(self, a, delta, dt): self.x = self.x + self.v * math.cos(self.yaw) * dt self.y = self.y + self.v * math.sin(self.yaw) * dt self.yaw = self.yaw + self.v / L * math.tan(delta) * dt self.v = self.v + a * dt
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L33-L37
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
92.307692
5
1
100
0
def update(self, a, delta, dt): self.x = self.x + self.v * math.cos(self.yaw) * dt self.y = self.y + self.v * math.sin(self.yaw) * dt self.yaw = self.yaw + self.v / L * math.tan(delta) * dt self.v = self.v + a * dt
667
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
CubicSplinePath.__init__
(self, x, y)
40
53
def __init__(self, x, y): x, y = map(np.asarray, (x, y)) s = np.append([0],(np.cumsum(np.diff(x)**2) + np.cumsum(np.diff(y)**2))**0.5) self.X = interpolate.CubicSpline(s, x) self.Y = interpolate.CubicSpline(s, y) self.dX = self.X.derivative(1) self.ddX = self.X.derivative(2) self.dY = self.Y.derivative(1) self.ddY = self.Y.derivative(2) self.length = s[-1]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L40-L53
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
92.307692
14
1
100
0
def __init__(self, x, y): x, y = map(np.asarray, (x, y)) s = np.append([0],(np.cumsum(np.diff(x)**2) + np.cumsum(np.diff(y)**2))**0.5) self.X = interpolate.CubicSpline(s, x) self.Y = interpolate.CubicSpline(s, y) self.dX = self.X.derivative(1) self.ddX = self.X.derivative(2) self.dY = self.Y.derivative(1) self.ddY = self.Y.derivative(2) self.length = s[-1]
668
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
CubicSplinePath.calc_yaw
(self, s)
return np.arctan2(dy, dx)
55
57
def calc_yaw(self, s): dx, dy = self.dX(s), self.dY(s) return np.arctan2(dy, dx)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L55-L57
2
[ 0, 1, 2 ]
100
[]
0
true
92.307692
3
1
100
0
def calc_yaw(self, s): dx, dy = self.dX(s), self.dY(s) return np.arctan2(dy, dx)
669
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
CubicSplinePath.calc_curvature
(self, s)
return (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))
59
62
def calc_curvature(self, s): dx, dy = self.dX(s), self.dY(s) ddx, ddy = self.ddX(s), self.ddY(s) return (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L59-L62
2
[ 0, 1, 2, 3 ]
100
[]
0
true
92.307692
4
1
100
0
def calc_curvature(self, s): dx, dy = self.dX(s), self.dY(s) ddx, ddy = self.ddX(s), self.ddY(s) return (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))
670
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
CubicSplinePath.__find_nearest_point
(self, s0, x, y)
return minimum
64
75
def __find_nearest_point(self, s0, x, y): def calc_distance(_s, *args): _x, _y= self.X(_s), self.Y(_s) return (_x - args[0])**2 + (_y - args[1])**2 def calc_distance_jacobian(_s, *args): _x, _y = self.X(_s), self.Y(_s) _dx, _dy = self.dX(_s), self.dY(_s) return 2*_dx*(_x - args[0])+2*_dy*(_y-args[1]) minimum = optimize.fmin_cg(calc_distance, s0, calc_distance_jacobian, args=(x, y), full_output=True, disp=False) return minimum
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L64-L75
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
92.307692
12
3
100
0
def __find_nearest_point(self, s0, x, y): def calc_distance(_s, *args): _x, _y= self.X(_s), self.Y(_s) return (_x - args[0])**2 + (_y - args[1])**2 def calc_distance_jacobian(_s, *args): _x, _y = self.X(_s), self.Y(_s) _dx, _dy = self.dX(_s), self.dY(_s) return 2*_dx*(_x - args[0])+2*_dy*(_y-args[1]) minimum = optimize.fmin_cg(calc_distance, s0, calc_distance_jacobian, args=(x, y), full_output=True, disp=False) return minimum
671
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
CubicSplinePath.calc_track_error
(self, x, y, s0)
return e, k, yaw, s
77
92
def calc_track_error(self, x, y, s0): ret = self.__find_nearest_point(s0, x, y) s = ret[0][0] e = ret[1] k = self.calc_curvature(s) yaw = self.calc_yaw(s) dxl = self.X(s) - x dyl = self.Y(s) - y angle = pi_2_pi(yaw - math.atan2(dyl, dxl)) if angle < 0: e*= -1 return e, k, yaw, s
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L77-L92
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
92.307692
16
2
100
0
def calc_track_error(self, x, y, s0): ret = self.__find_nearest_point(s0, x, y) s = ret[0][0] e = ret[1] k = self.calc_curvature(s) yaw = self.calc_yaw(s) dxl = self.X(s) - x dyl = self.Y(s) - y angle = pi_2_pi(yaw - math.atan2(dyl, dxl)) if angle < 0: e*= -1 return e, k, yaw, s
672
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
pid_control
(target, current)
return Kp * (target - current)
Proportional control for the speed. :param target: (float) :param current: (float) :return: (float)
Proportional control for the speed.
65
73
def pid_control(target, current): """ Proportional control for the speed. :param target: (float) :param current: (float) :return: (float) """ return Kp * (target - current)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L65-L73
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
98.75
9
1
100
5
def pid_control(target, current): return Kp * (target - current)
673
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
stanley_control
(state, cx, cy, cyaw, last_target_idx)
return delta, current_target_idx
Stanley steering control. :param state: (State object) :param cx: ([float]) :param cy: ([float]) :param cyaw: ([float]) :param last_target_idx: (int) :return: (float, int)
Stanley steering control.
76
99
def stanley_control(state, cx, cy, cyaw, last_target_idx): """ Stanley steering control. :param state: (State object) :param cx: ([float]) :param cy: ([float]) :param cyaw: ([float]) :param last_target_idx: (int) :return: (float, int) """ current_target_idx, error_front_axle = calc_target_index(state, cx, cy) if last_target_idx >= current_target_idx: current_target_idx = last_target_idx # theta_e corrects the heading error theta_e = normalize_angle(cyaw[current_target_idx] - state.yaw) # theta_d corrects the cross track error theta_d = np.arctan2(k * error_front_axle, state.v) # Steering control delta = theta_e + theta_d return delta, current_target_idx
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L76-L99
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
100
[]
0
true
98.75
24
2
100
8
def stanley_control(state, cx, cy, cyaw, last_target_idx): current_target_idx, error_front_axle = calc_target_index(state, cx, cy) if last_target_idx >= current_target_idx: current_target_idx = last_target_idx # theta_e corrects the heading error theta_e = normalize_angle(cyaw[current_target_idx] - state.yaw) # theta_d corrects the cross track error theta_d = np.arctan2(k * error_front_axle, state.v) # Steering control delta = theta_e + theta_d return delta, current_target_idx
674
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
normalize_angle
(angle)
return angle
Normalize an angle to [-pi, pi]. :param angle: (float) :return: (float) Angle in radian in [-pi, pi]
Normalize an angle to [-pi, pi].
102
115
def normalize_angle(angle): """ Normalize an angle to [-pi, pi]. :param angle: (float) :return: (float) Angle in radian in [-pi, pi] """ while angle > np.pi: angle -= 2.0 * np.pi while angle < -np.pi: angle += 2.0 * np.pi return angle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L102-L115
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
98.75
14
3
100
4
def normalize_angle(angle): while angle > np.pi: angle -= 2.0 * np.pi while angle < -np.pi: angle += 2.0 * np.pi return angle
675
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
calc_target_index
(state, cx, cy)
return target_idx, error_front_axle
Compute index in the trajectory list of the target. :param state: (State object) :param cx: [float] :param cy: [float] :return: (int, float)
Compute index in the trajectory list of the target.
118
142
def calc_target_index(state, cx, cy): """ Compute index in the trajectory list of the target. :param state: (State object) :param cx: [float] :param cy: [float] :return: (int, float) """ # Calc front axle position fx = state.x + L * np.cos(state.yaw) fy = state.y + L * np.sin(state.yaw) # Search nearest point index dx = [fx - icx for icx in cx] dy = [fy - icy for icy in cy] d = np.hypot(dx, dy) target_idx = np.argmin(d) # Project RMS error onto front axle vector front_axle_vec = [-np.cos(state.yaw + np.pi / 2), -np.sin(state.yaw + np.pi / 2)] error_front_axle = np.dot([dx[target_idx], dy[target_idx]], front_axle_vec) return target_idx, error_front_axle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L118-L142
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
98.75
25
3
100
6
def calc_target_index(state, cx, cy): # Calc front axle position fx = state.x + L * np.cos(state.yaw) fy = state.y + L * np.sin(state.yaw) # Search nearest point index dx = [fx - icx for icx in cx] dy = [fy - icy for icy in cy] d = np.hypot(dx, dy) target_idx = np.argmin(d) # Project RMS error onto front axle vector front_axle_vec = [-np.cos(state.yaw + np.pi / 2), -np.sin(state.yaw + np.pi / 2)] error_front_axle = np.dot([dx[target_idx], dy[target_idx]], front_axle_vec) return target_idx, error_front_axle
676
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
main
()
Plot an example of Stanley steering control on a cubic spline.
Plot an example of Stanley steering control on a cubic spline.
145
213
def main(): """Plot an example of Stanley steering control on a cubic spline.""" # target course ax = [0.0, 100.0, 100.0, 50.0, 60.0] ay = [0.0, 0.0, -30.0, -20.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=0.1) target_speed = 30.0 / 3.6 # [m/s] max_simulation_time = 100.0 # Initial state state = State(x=-0.0, y=5.0, yaw=np.radians(20.0), v=0.0) last_idx = len(cx) - 1 time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] target_idx, _ = calc_target_index(state, cx, cy) while max_simulation_time >= time and last_idx > target_idx: ai = pid_control(target_speed, state.v) di, target_idx = stanley_control(state, cx, cy, cyaw, target_idx) state.update(ai, di) time += dt x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.plot(cx[target_idx], cy[target_idx], "xg", label="target") plt.axis("equal") plt.grid(True) plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4]) plt.pause(0.001) # Test assert last_idx >= target_idx, "Cannot reach goal" if show_animation: # pragma: no cover plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.legend() plt.xlabel("x[m]") plt.ylabel("y[m]") plt.axis("equal") plt.grid(True) plt.subplots(1) plt.plot(t, [iv * 3.6 for iv in v], "-r") plt.xlabel("Time[s]") plt.ylabel("Speed[km/h]") plt.grid(True) plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L145-L213
2
[ 0, 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 ]
153.333333
[]
0
true
98.75
69
7
100
1
def main(): # target course ax = [0.0, 100.0, 100.0, 50.0, 60.0] ay = [0.0, 0.0, -30.0, -20.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=0.1) target_speed = 30.0 / 3.6 # [m/s] max_simulation_time = 100.0 # Initial state state = State(x=-0.0, y=5.0, yaw=np.radians(20.0), v=0.0) last_idx = len(cx) - 1 time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] target_idx, _ = calc_target_index(state, cx, cy) while max_simulation_time >= time and last_idx > target_idx: ai = pid_control(target_speed, state.v) di, target_idx = stanley_control(state, cx, cy, cyaw, target_idx) state.update(ai, di) time += dt x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.plot(cx[target_idx], cy[target_idx], "xg", label="target") plt.axis("equal") plt.grid(True) plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4]) plt.pause(0.001) # Test assert last_idx >= target_idx, "Cannot reach goal" if show_animation: # pragma: no cover plt.plot(cx, cy, ".r", label="course") plt.plot(x, y, "-b", label="trajectory") plt.legend() plt.xlabel("x[m]") plt.ylabel("y[m]") plt.axis("equal") plt.grid(True) plt.subplots(1) plt.plot(t, [iv * 3.6 for iv in v], "-r") plt.xlabel("Time[s]") plt.ylabel("Speed[km/h]") plt.grid(True) plt.show()
677
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0)
Instantiate the object.
Instantiate the object.
39
45
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): """Instantiate the object.""" super(State, self).__init__() self.x = x self.y = y self.yaw = yaw self.v = v
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L39-L45
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
98.75
7
1
100
1
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): super(State, self).__init__() self.x = x self.y = y self.yaw = yaw self.v = v
678
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/stanley_controller/stanley_controller.py
State.update
(self, acceleration, delta)
Update the state of the vehicle. Stanley Control uses bicycle model. :param acceleration: (float) Acceleration :param delta: (float) Steering
Update the state of the vehicle.
47
62
def update(self, acceleration, delta): """ Update the state of the vehicle. Stanley Control uses bicycle model. :param acceleration: (float) Acceleration :param delta: (float) Steering """ delta = np.clip(delta, -max_steer, max_steer) self.x += self.v * np.cos(self.yaw) * dt self.y += self.v * np.sin(self.yaw) * dt self.yaw += self.v / L * np.tan(delta) * dt self.yaw = normalize_angle(self.yaw) self.v += acceleration * dt
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/stanley_controller/stanley_controller.py#L47-L62
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
98.75
16
1
100
6
def update(self, acceleration, delta): delta = np.clip(delta, -max_steer, max_steer) self.x += self.v * np.cos(self.yaw) * dt self.y += self.v * np.sin(self.yaw) * dt self.yaw += self.v / L * np.tan(delta) * dt self.yaw = normalize_angle(self.yaw) self.v += acceleration * dt
679
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
pi_2_pi
(angle)
return angle
71
78
def pi_2_pi(angle): while(angle > math.pi): angle = angle - 2.0 * math.pi while(angle < -math.pi): angle = angle + 2.0 * math.pi return angle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L71-L78
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
94.136808
8
3
100
0
def pi_2_pi(angle): while(angle > math.pi): angle = angle - 2.0 * math.pi while(angle < -math.pi): angle = angle + 2.0 * math.pi return angle
680
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_linear_model_matrix
(v, phi, delta)
return A, B, C
81
103
def get_linear_model_matrix(v, phi, delta): A = np.zeros((NX, NX)) A[0, 0] = 1.0 A[1, 1] = 1.0 A[2, 2] = 1.0 A[3, 3] = 1.0 A[0, 2] = DT * math.cos(phi) A[0, 3] = - DT * v * math.sin(phi) A[1, 2] = DT * math.sin(phi) A[1, 3] = DT * v * math.cos(phi) A[3, 2] = DT * math.tan(delta) / WB B = np.zeros((NX, NU)) B[2, 0] = DT B[3, 1] = DT * v / (WB * math.cos(delta) ** 2) C = np.zeros(NX) C[0] = DT * v * math.sin(phi) * phi C[1] = - DT * v * math.cos(phi) * phi C[3] = - DT * v * delta / (WB * math.cos(delta) ** 2) return A, B, C
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L81-L103
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
94.136808
23
1
100
0
def get_linear_model_matrix(v, phi, delta): A = np.zeros((NX, NX)) A[0, 0] = 1.0 A[1, 1] = 1.0 A[2, 2] = 1.0 A[3, 3] = 1.0 A[0, 2] = DT * math.cos(phi) A[0, 3] = - DT * v * math.sin(phi) A[1, 2] = DT * math.sin(phi) A[1, 3] = DT * v * math.cos(phi) A[3, 2] = DT * math.tan(delta) / WB B = np.zeros((NX, NU)) B[2, 0] = DT B[3, 1] = DT * v / (WB * math.cos(delta) ** 2) C = np.zeros(NX) C[0] = DT * v * math.sin(phi) * phi C[1] = - DT * v * math.cos(phi) * phi C[3] = - DT * v * delta / (WB * math.cos(delta) ** 2) return A, B, C
681
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
plot_car
(x, y, yaw, steer=0.0, cabcolor="-r", truckcolor="-k")
106
159
def plot_car(x, y, yaw, steer=0.0, cabcolor="-r", truckcolor="-k"): # pragma: no cover outline = np.array([[-BACKTOWHEEL, (LENGTH - BACKTOWHEEL), (LENGTH - BACKTOWHEEL), -BACKTOWHEEL, -BACKTOWHEEL], [WIDTH / 2, WIDTH / 2, - WIDTH / 2, -WIDTH / 2, WIDTH / 2]]) fr_wheel = np.array([[WHEEL_LEN, -WHEEL_LEN, -WHEEL_LEN, WHEEL_LEN, WHEEL_LEN], [-WHEEL_WIDTH - TREAD, -WHEEL_WIDTH - TREAD, WHEEL_WIDTH - TREAD, WHEEL_WIDTH - TREAD, -WHEEL_WIDTH - TREAD]]) rr_wheel = np.copy(fr_wheel) fl_wheel = np.copy(fr_wheel) fl_wheel[1, :] *= -1 rl_wheel = np.copy(rr_wheel) rl_wheel[1, :] *= -1 Rot1 = np.array([[math.cos(yaw), math.sin(yaw)], [-math.sin(yaw), math.cos(yaw)]]) Rot2 = np.array([[math.cos(steer), math.sin(steer)], [-math.sin(steer), math.cos(steer)]]) fr_wheel = (fr_wheel.T.dot(Rot2)).T fl_wheel = (fl_wheel.T.dot(Rot2)).T fr_wheel[0, :] += WB fl_wheel[0, :] += WB fr_wheel = (fr_wheel.T.dot(Rot1)).T fl_wheel = (fl_wheel.T.dot(Rot1)).T outline = (outline.T.dot(Rot1)).T rr_wheel = (rr_wheel.T.dot(Rot1)).T rl_wheel = (rl_wheel.T.dot(Rot1)).T outline[0, :] += x outline[1, :] += y fr_wheel[0, :] += x fr_wheel[1, :] += y rr_wheel[0, :] += x rr_wheel[1, :] += y fl_wheel[0, :] += x fl_wheel[1, :] += y rl_wheel[0, :] += x rl_wheel[1, :] += y plt.plot(np.array(outline[0, :]).flatten(), np.array(outline[1, :]).flatten(), truckcolor) plt.plot(np.array(fr_wheel[0, :]).flatten(), np.array(fr_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(rr_wheel[0, :]).flatten(), np.array(rr_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(fl_wheel[0, :]).flatten(), np.array(fl_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(rl_wheel[0, :]).flatten(), np.array(rl_wheel[1, :]).flatten(), truckcolor) plt.plot(x, y, "*")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L106-L159
2
[]
0
[]
0
false
94.136808
54
1
100
0
def plot_car(x, y, yaw, steer=0.0, cabcolor="-r", truckcolor="-k"): # pragma: no cover outline = np.array([[-BACKTOWHEEL, (LENGTH - BACKTOWHEEL), (LENGTH - BACKTOWHEEL), -BACKTOWHEEL, -BACKTOWHEEL], [WIDTH / 2, WIDTH / 2, - WIDTH / 2, -WIDTH / 2, WIDTH / 2]]) fr_wheel = np.array([[WHEEL_LEN, -WHEEL_LEN, -WHEEL_LEN, WHEEL_LEN, WHEEL_LEN], [-WHEEL_WIDTH - TREAD, -WHEEL_WIDTH - TREAD, WHEEL_WIDTH - TREAD, WHEEL_WIDTH - TREAD, -WHEEL_WIDTH - TREAD]]) rr_wheel = np.copy(fr_wheel) fl_wheel = np.copy(fr_wheel) fl_wheel[1, :] *= -1 rl_wheel = np.copy(rr_wheel) rl_wheel[1, :] *= -1 Rot1 = np.array([[math.cos(yaw), math.sin(yaw)], [-math.sin(yaw), math.cos(yaw)]]) Rot2 = np.array([[math.cos(steer), math.sin(steer)], [-math.sin(steer), math.cos(steer)]]) fr_wheel = (fr_wheel.T.dot(Rot2)).T fl_wheel = (fl_wheel.T.dot(Rot2)).T fr_wheel[0, :] += WB fl_wheel[0, :] += WB fr_wheel = (fr_wheel.T.dot(Rot1)).T fl_wheel = (fl_wheel.T.dot(Rot1)).T outline = (outline.T.dot(Rot1)).T rr_wheel = (rr_wheel.T.dot(Rot1)).T rl_wheel = (rl_wheel.T.dot(Rot1)).T outline[0, :] += x outline[1, :] += y fr_wheel[0, :] += x fr_wheel[1, :] += y rr_wheel[0, :] += x rr_wheel[1, :] += y fl_wheel[0, :] += x fl_wheel[1, :] += y rl_wheel[0, :] += x rl_wheel[1, :] += y plt.plot(np.array(outline[0, :]).flatten(), np.array(outline[1, :]).flatten(), truckcolor) plt.plot(np.array(fr_wheel[0, :]).flatten(), np.array(fr_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(rr_wheel[0, :]).flatten(), np.array(rr_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(fl_wheel[0, :]).flatten(), np.array(fl_wheel[1, :]).flatten(), truckcolor) plt.plot(np.array(rl_wheel[0, :]).flatten(), np.array(rl_wheel[1, :]).flatten(), truckcolor) plt.plot(x, y, "*")
682
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
update_state
(state, a, delta)
return state
162
180
def update_state(state, a, delta): # input check if delta >= MAX_STEER: delta = MAX_STEER elif delta <= -MAX_STEER: delta = -MAX_STEER state.x = state.x + state.v * math.cos(state.yaw) * DT state.y = state.y + state.v * math.sin(state.yaw) * DT state.yaw = state.yaw + state.v / WB * math.tan(delta) * DT state.v = state.v + a * DT if state.v > MAX_SPEED: state.v = MAX_SPEED elif state.v < MIN_SPEED: state.v = MIN_SPEED return state
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L162-L180
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 17, 18 ]
89.473684
[ 14, 16 ]
10.526316
false
94.136808
19
5
89.473684
0
def update_state(state, a, delta): # input check if delta >= MAX_STEER: delta = MAX_STEER elif delta <= -MAX_STEER: delta = -MAX_STEER state.x = state.x + state.v * math.cos(state.yaw) * DT state.y = state.y + state.v * math.sin(state.yaw) * DT state.yaw = state.yaw + state.v / WB * math.tan(delta) * DT state.v = state.v + a * DT if state.v > MAX_SPEED: state.v = MAX_SPEED elif state.v < MIN_SPEED: state.v = MIN_SPEED return state
683
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_nparray_from_matrix
(x)
return np.array(x).flatten()
183
184
def get_nparray_from_matrix(x): return np.array(x).flatten()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L183-L184
2
[ 0, 1 ]
100
[]
0
true
94.136808
2
1
100
0
def get_nparray_from_matrix(x): return np.array(x).flatten()
684
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
calc_nearest_index
(state, cx, cy, cyaw, pind)
return ind, mind
187
207
def calc_nearest_index(state, cx, cy, cyaw, pind): dx = [state.x - icx for icx in cx[pind:(pind + N_IND_SEARCH)]] dy = [state.y - icy for icy in cy[pind:(pind + N_IND_SEARCH)]] d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)] mind = min(d) ind = d.index(mind) + pind mind = math.sqrt(mind) dxl = cx[ind] - state.x dyl = cy[ind] - state.y angle = pi_2_pi(cyaw[ind] - math.atan2(dyl, dxl)) if angle < 0: mind *= -1 return ind, mind
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L187-L207
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
94.136808
21
5
100
0
def calc_nearest_index(state, cx, cy, cyaw, pind): dx = [state.x - icx for icx in cx[pind:(pind + N_IND_SEARCH)]] dy = [state.y - icy for icy in cy[pind:(pind + N_IND_SEARCH)]] d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)] mind = min(d) ind = d.index(mind) + pind mind = math.sqrt(mind) dxl = cx[ind] - state.x dyl = cy[ind] - state.y angle = pi_2_pi(cyaw[ind] - math.atan2(dyl, dxl)) if angle < 0: mind *= -1 return ind, mind
685
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
predict_motion
(x0, oa, od, xref)
return xbar
210
223
def predict_motion(x0, oa, od, xref): xbar = xref * 0.0 for i, _ in enumerate(x0): xbar[i, 0] = x0[i] state = State(x=x0[0], y=x0[1], yaw=x0[3], v=x0[2]) for (ai, di, i) in zip(oa, od, range(1, T + 1)): state = update_state(state, ai, di) xbar[0, i] = state.x xbar[1, i] = state.y xbar[2, i] = state.v xbar[3, i] = state.yaw return xbar
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L210-L223
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
94.136808
14
3
100
0
def predict_motion(x0, oa, od, xref): xbar = xref * 0.0 for i, _ in enumerate(x0): xbar[i, 0] = x0[i] state = State(x=x0[0], y=x0[1], yaw=x0[3], v=x0[2]) for (ai, di, i) in zip(oa, od, range(1, T + 1)): state = update_state(state, ai, di) xbar[0, i] = state.x xbar[1, i] = state.y xbar[2, i] = state.v xbar[3, i] = state.yaw return xbar
686
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
iterative_linear_mpc_control
(xref, x0, dref, oa, od)
return oa, od, ox, oy, oyaw, ov
MPC contorl with updating operational point iteraitvely
MPC contorl with updating operational point iteraitvely
226
245
def iterative_linear_mpc_control(xref, x0, dref, oa, od): """ MPC contorl with updating operational point iteraitvely """ if oa is None or od is None: oa = [0.0] * T od = [0.0] * T for i in range(MAX_ITER): xbar = predict_motion(x0, oa, od, xref) poa, pod = oa[:], od[:] oa, od, ox, oy, oyaw, ov = linear_mpc_control(xref, xbar, x0, dref) du = sum(abs(oa - poa)) + sum(abs(od - pod)) # calc u change value if du <= DU_TH: break else: print("Iterative is max iter") return oa, od, ox, oy, oyaw, ov
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L226-L245
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
94.136808
20
5
100
1
def iterative_linear_mpc_control(xref, x0, dref, oa, od): if oa is None or od is None: oa = [0.0] * T od = [0.0] * T for i in range(MAX_ITER): xbar = predict_motion(x0, oa, od, xref) poa, pod = oa[:], od[:] oa, od, ox, oy, oyaw, ov = linear_mpc_control(xref, xbar, x0, dref) du = sum(abs(oa - poa)) + sum(abs(od - pod)) # calc u change value if du <= DU_TH: break else: print("Iterative is max iter") return oa, od, ox, oy, oyaw, ov
687
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
linear_mpc_control
(xref, xbar, x0, dref)
return oa, odelta, ox, oy, oyaw, ov
linear mpc control xref: reference point xbar: operational point x0: initial state dref: reference steer angle
linear mpc control
248
302
def linear_mpc_control(xref, xbar, x0, dref): """ linear mpc control xref: reference point xbar: operational point x0: initial state dref: reference steer angle """ x = cvxpy.Variable((NX, T + 1)) u = cvxpy.Variable((NU, T)) cost = 0.0 constraints = [] for t in range(T): cost += cvxpy.quad_form(u[:, t], R) if t != 0: cost += cvxpy.quad_form(xref[:, t] - x[:, t], Q) A, B, C = get_linear_model_matrix( xbar[2, t], xbar[3, t], dref[0, t]) constraints += [x[:, t + 1] == A @ x[:, t] + B @ u[:, t] + C] if t < (T - 1): cost += cvxpy.quad_form(u[:, t + 1] - u[:, t], Rd) constraints += [cvxpy.abs(u[1, t + 1] - u[1, t]) <= MAX_DSTEER * DT] cost += cvxpy.quad_form(xref[:, T] - x[:, T], Qf) constraints += [x[:, 0] == x0] constraints += [x[2, :] <= MAX_SPEED] constraints += [x[2, :] >= MIN_SPEED] constraints += [cvxpy.abs(u[0, :]) <= MAX_ACCEL] constraints += [cvxpy.abs(u[1, :]) <= MAX_STEER] prob = cvxpy.Problem(cvxpy.Minimize(cost), constraints) prob.solve(solver=cvxpy.ECOS, verbose=False) if prob.status == cvxpy.OPTIMAL or prob.status == cvxpy.OPTIMAL_INACCURATE: ox = get_nparray_from_matrix(x.value[0, :]) oy = get_nparray_from_matrix(x.value[1, :]) ov = get_nparray_from_matrix(x.value[2, :]) oyaw = get_nparray_from_matrix(x.value[3, :]) oa = get_nparray_from_matrix(u.value[0, :]) odelta = get_nparray_from_matrix(u.value[1, :]) else: print("Error: Cannot solve mpc..") oa, odelta, ox, oy, oyaw, ov = None, None, None, None, None, None return oa, odelta, ox, oy, oyaw, ov
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L248-L302
2
[ 0, 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, 53, 54 ]
96.363636
[ 51, 52 ]
3.636364
false
94.136808
55
6
96.363636
6
def linear_mpc_control(xref, xbar, x0, dref): x = cvxpy.Variable((NX, T + 1)) u = cvxpy.Variable((NU, T)) cost = 0.0 constraints = [] for t in range(T): cost += cvxpy.quad_form(u[:, t], R) if t != 0: cost += cvxpy.quad_form(xref[:, t] - x[:, t], Q) A, B, C = get_linear_model_matrix( xbar[2, t], xbar[3, t], dref[0, t]) constraints += [x[:, t + 1] == A @ x[:, t] + B @ u[:, t] + C] if t < (T - 1): cost += cvxpy.quad_form(u[:, t + 1] - u[:, t], Rd) constraints += [cvxpy.abs(u[1, t + 1] - u[1, t]) <= MAX_DSTEER * DT] cost += cvxpy.quad_form(xref[:, T] - x[:, T], Qf) constraints += [x[:, 0] == x0] constraints += [x[2, :] <= MAX_SPEED] constraints += [x[2, :] >= MIN_SPEED] constraints += [cvxpy.abs(u[0, :]) <= MAX_ACCEL] constraints += [cvxpy.abs(u[1, :]) <= MAX_STEER] prob = cvxpy.Problem(cvxpy.Minimize(cost), constraints) prob.solve(solver=cvxpy.ECOS, verbose=False) if prob.status == cvxpy.OPTIMAL or prob.status == cvxpy.OPTIMAL_INACCURATE: ox = get_nparray_from_matrix(x.value[0, :]) oy = get_nparray_from_matrix(x.value[1, :]) ov = get_nparray_from_matrix(x.value[2, :]) oyaw = get_nparray_from_matrix(x.value[3, :]) oa = get_nparray_from_matrix(u.value[0, :]) odelta = get_nparray_from_matrix(u.value[1, :]) else: print("Error: Cannot solve mpc..") oa, odelta, ox, oy, oyaw, ov = None, None, None, None, None, None return oa, odelta, ox, oy, oyaw, ov
688
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
calc_ref_trajectory
(state, cx, cy, cyaw, ck, sp, dl, pind)
return xref, ind, dref
305
340
def calc_ref_trajectory(state, cx, cy, cyaw, ck, sp, dl, pind): xref = np.zeros((NX, T + 1)) dref = np.zeros((1, T + 1)) ncourse = len(cx) ind, _ = calc_nearest_index(state, cx, cy, cyaw, pind) if pind >= ind: ind = pind xref[0, 0] = cx[ind] xref[1, 0] = cy[ind] xref[2, 0] = sp[ind] xref[3, 0] = cyaw[ind] dref[0, 0] = 0.0 # steer operational point should be 0 travel = 0.0 for i in range(T + 1): travel += abs(state.v) * DT dind = int(round(travel / dl)) if (ind + dind) < ncourse: xref[0, i] = cx[ind + dind] xref[1, i] = cy[ind + dind] xref[2, i] = sp[ind + dind] xref[3, i] = cyaw[ind + dind] dref[0, i] = 0.0 else: xref[0, i] = cx[ncourse - 1] xref[1, i] = cy[ncourse - 1] xref[2, i] = sp[ncourse - 1] xref[3, i] = cyaw[ncourse - 1] dref[0, i] = 0.0 return xref, ind, dref
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L305-L340
2
[ 0, 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, 29, 30, 31, 32, 33, 34, 35 ]
97.222222
[]
0
false
94.136808
36
4
100
0
def calc_ref_trajectory(state, cx, cy, cyaw, ck, sp, dl, pind): xref = np.zeros((NX, T + 1)) dref = np.zeros((1, T + 1)) ncourse = len(cx) ind, _ = calc_nearest_index(state, cx, cy, cyaw, pind) if pind >= ind: ind = pind xref[0, 0] = cx[ind] xref[1, 0] = cy[ind] xref[2, 0] = sp[ind] xref[3, 0] = cyaw[ind] dref[0, 0] = 0.0 # steer operational point should be 0 travel = 0.0 for i in range(T + 1): travel += abs(state.v) * DT dind = int(round(travel / dl)) if (ind + dind) < ncourse: xref[0, i] = cx[ind + dind] xref[1, i] = cy[ind + dind] xref[2, i] = sp[ind + dind] xref[3, i] = cyaw[ind + dind] dref[0, i] = 0.0 else: xref[0, i] = cx[ncourse - 1] xref[1, i] = cy[ncourse - 1] xref[2, i] = sp[ncourse - 1] xref[3, i] = cyaw[ncourse - 1] dref[0, i] = 0.0 return xref, ind, dref
689
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
check_goal
(state, goal, tind, nind)
return False
343
360
def check_goal(state, goal, tind, nind): # check goal dx = state.x - goal[0] dy = state.y - goal[1] d = math.hypot(dx, dy) isgoal = (d <= GOAL_DIS) if abs(tind - nind) >= 5: isgoal = False isstop = (abs(state.v) <= STOP_SPEED) if isgoal and isstop: return True return False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L343-L360
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
94.136808
18
4
100
0
def check_goal(state, goal, tind, nind): # check goal dx = state.x - goal[0] dy = state.y - goal[1] d = math.hypot(dx, dy) isgoal = (d <= GOAL_DIS) if abs(tind - nind) >= 5: isgoal = False isstop = (abs(state.v) <= STOP_SPEED) if isgoal and isstop: return True return False
690
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
do_simulation
(cx, cy, cyaw, ck, sp, dl, initial_state)
return t, x, y, yaw, v, d, a
Simulation cx: course x position list cy: course y position list cy: course yaw position list ck: course curvature list sp: speed profile dl: course tick [m]
Simulation
363
445
def do_simulation(cx, cy, cyaw, ck, sp, dl, initial_state): """ Simulation cx: course x position list cy: course y position list cy: course yaw position list ck: course curvature list sp: speed profile dl: course tick [m] """ goal = [cx[-1], cy[-1]] state = initial_state # initial yaw compensation if state.yaw - cyaw[0] >= math.pi: state.yaw -= math.pi * 2.0 elif state.yaw - cyaw[0] <= -math.pi: state.yaw += math.pi * 2.0 time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] d = [0.0] a = [0.0] target_ind, _ = calc_nearest_index(state, cx, cy, cyaw, 0) odelta, oa = None, None cyaw = smooth_yaw(cyaw) while MAX_TIME >= time: xref, target_ind, dref = calc_ref_trajectory( state, cx, cy, cyaw, ck, sp, dl, target_ind) x0 = [state.x, state.y, state.v, state.yaw] # current state oa, odelta, ox, oy, oyaw, ov = iterative_linear_mpc_control( xref, x0, dref, oa, odelta) if odelta is not None: di, ai = odelta[0], oa[0] state = update_state(state, ai, di) time = time + DT x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) d.append(di) a.append(ai) if check_goal(state, goal, target_ind, len(cx)): print("Goal") break if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) if ox is not None: plt.plot(ox, oy, "xr", label="MPC") plt.plot(cx, cy, "-r", label="course") plt.plot(x, y, "ob", label="trajectory") plt.plot(xref[0, :], xref[1, :], "xk", label="xref") plt.plot(cx[target_ind], cy[target_ind], "xg", label="target") plot_car(state.x, state.y, state.yaw, steer=di) plt.axis("equal") plt.grid(True) plt.title("Time[s]:" + str(round(time, 2)) + ", speed[km/h]:" + str(round(state.v * 3.6, 2))) plt.pause(0.0001) return t, x, y, yaw, v, d, a
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L363-L445
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 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 ]
118.84058
[ 21 ]
1.449275
false
94.136808
83
8
98.550725
8
def do_simulation(cx, cy, cyaw, ck, sp, dl, initial_state): goal = [cx[-1], cy[-1]] state = initial_state # initial yaw compensation if state.yaw - cyaw[0] >= math.pi: state.yaw -= math.pi * 2.0 elif state.yaw - cyaw[0] <= -math.pi: state.yaw += math.pi * 2.0 time = 0.0 x = [state.x] y = [state.y] yaw = [state.yaw] v = [state.v] t = [0.0] d = [0.0] a = [0.0] target_ind, _ = calc_nearest_index(state, cx, cy, cyaw, 0) odelta, oa = None, None cyaw = smooth_yaw(cyaw) while MAX_TIME >= time: xref, target_ind, dref = calc_ref_trajectory( state, cx, cy, cyaw, ck, sp, dl, target_ind) x0 = [state.x, state.y, state.v, state.yaw] # current state oa, odelta, ox, oy, oyaw, ov = iterative_linear_mpc_control( xref, x0, dref, oa, odelta) if odelta is not None: di, ai = odelta[0], oa[0] state = update_state(state, ai, di) time = time + DT x.append(state.x) y.append(state.y) yaw.append(state.yaw) v.append(state.v) t.append(time) d.append(di) a.append(ai) if check_goal(state, goal, target_ind, len(cx)): print("Goal") break if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) if ox is not None: plt.plot(ox, oy, "xr", label="MPC") plt.plot(cx, cy, "-r", label="course") plt.plot(x, y, "ob", label="trajectory") plt.plot(xref[0, :], xref[1, :], "xk", label="xref") plt.plot(cx[target_ind], cy[target_ind], "xg", label="target") plot_car(state.x, state.y, state.yaw, steer=di) plt.axis("equal") plt.grid(True) plt.title("Time[s]:" + str(round(time, 2)) + ", speed[km/h]:" + str(round(state.v * 3.6, 2))) plt.pause(0.0001) return t, x, y, yaw, v, d, a
691
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
calc_speed_profile
(cx, cy, cyaw, target_speed)
return speed_profile
448
474
def calc_speed_profile(cx, cy, cyaw, target_speed): speed_profile = [target_speed] * len(cx) direction = 1.0 # forward # Set stop point for i in range(len(cx) - 1): dx = cx[i + 1] - cx[i] dy = cy[i + 1] - cy[i] move_direction = math.atan2(dy, dx) if dx != 0.0 and dy != 0.0: dangle = abs(pi_2_pi(move_direction - cyaw[i])) if dangle >= math.pi / 4.0: direction = -1.0 else: direction = 1.0 if direction != 1.0: speed_profile[i] = - target_speed else: speed_profile[i] = target_speed speed_profile[-1] = 0.0 return speed_profile
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L448-L474
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 22, 23, 24, 25, 26 ]
92.592593
[]
0
false
94.136808
27
6
100
0
def calc_speed_profile(cx, cy, cyaw, target_speed): speed_profile = [target_speed] * len(cx) direction = 1.0 # forward # Set stop point for i in range(len(cx) - 1): dx = cx[i + 1] - cx[i] dy = cy[i + 1] - cy[i] move_direction = math.atan2(dy, dx) if dx != 0.0 and dy != 0.0: dangle = abs(pi_2_pi(move_direction - cyaw[i])) if dangle >= math.pi / 4.0: direction = -1.0 else: direction = 1.0 if direction != 1.0: speed_profile[i] = - target_speed else: speed_profile[i] = target_speed speed_profile[-1] = 0.0 return speed_profile
692
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
smooth_yaw
(yaw)
return yaw
477
490
def smooth_yaw(yaw): for i in range(len(yaw) - 1): dyaw = yaw[i + 1] - yaw[i] while dyaw >= math.pi / 2.0: yaw[i + 1] -= math.pi * 2.0 dyaw = yaw[i + 1] - yaw[i] while dyaw <= -math.pi / 2.0: yaw[i + 1] += math.pi * 2.0 dyaw = yaw[i + 1] - yaw[i] return yaw
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L477-L490
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
94.136808
14
4
100
0
def smooth_yaw(yaw): for i in range(len(yaw) - 1): dyaw = yaw[i + 1] - yaw[i] while dyaw >= math.pi / 2.0: yaw[i + 1] -= math.pi * 2.0 dyaw = yaw[i + 1] - yaw[i] while dyaw <= -math.pi / 2.0: yaw[i + 1] += math.pi * 2.0 dyaw = yaw[i + 1] - yaw[i] return yaw
693
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_straight_course
(dl)
return cx, cy, cyaw, ck
493
499
def get_straight_course(dl): ax = [0.0, 5.0, 10.0, 20.0, 30.0, 40.0, 50.0] ay = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L493-L499
2
[ 0 ]
14.285714
[ 1, 2, 3, 6 ]
57.142857
false
94.136808
7
1
42.857143
0
def get_straight_course(dl): ax = [0.0, 5.0, 10.0, 20.0, 30.0, 40.0, 50.0] ay = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
694
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_straight_course2
(dl)
return cx, cy, cyaw, ck
502
508
def get_straight_course2(dl): ax = [0.0, -10.0, -20.0, -40.0, -50.0, -60.0, -70.0] ay = [0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L502-L508
2
[ 0 ]
14.285714
[ 1, 2, 3, 6 ]
57.142857
false
94.136808
7
1
42.857143
0
def get_straight_course2(dl): ax = [0.0, -10.0, -20.0, -40.0, -50.0, -60.0, -70.0] ay = [0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
695
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_straight_course3
(dl)
return cx, cy, cyaw, ck
511
519
def get_straight_course3(dl): ax = [0.0, -10.0, -20.0, -40.0, -50.0, -60.0, -70.0] ay = [0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) cyaw = [i - math.pi for i in cyaw] return cx, cy, cyaw, ck
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L511-L519
2
[ 0, 1, 2, 3, 5, 6, 7, 8 ]
88.888889
[]
0
false
94.136808
9
2
100
0
def get_straight_course3(dl): ax = [0.0, -10.0, -20.0, -40.0, -50.0, -60.0, -70.0] ay = [0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) cyaw = [i - math.pi for i in cyaw] return cx, cy, cyaw, ck
696
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_forward_course
(dl)
return cx, cy, cyaw, ck
522
528
def get_forward_course(dl): ax = [0.0, 60.0, 125.0, 50.0, 75.0, 30.0, -10.0] ay = [0.0, 0.0, 50.0, 65.0, 30.0, 50.0, -20.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L522-L528
2
[ 0 ]
14.285714
[ 1, 2, 3, 6 ]
57.142857
false
94.136808
7
1
42.857143
0
def get_forward_course(dl): ax = [0.0, 60.0, 125.0, 50.0, 75.0, 30.0, -10.0] ay = [0.0, 0.0, 50.0, 65.0, 30.0, 50.0, -20.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) return cx, cy, cyaw, ck
697
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
get_switch_back_course
(dl)
return cx, cy, cyaw, ck
531
546
def get_switch_back_course(dl): ax = [0.0, 30.0, 6.0, 20.0, 35.0] ay = [0.0, 0.0, 20.0, 35.0, 20.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) ax = [35.0, 10.0, 0.0, 0.0] ay = [20.0, 30.0, 5.0, 0.0] cx2, cy2, cyaw2, ck2, s2 = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) cyaw2 = [i - math.pi for i in cyaw2] cx.extend(cx2) cy.extend(cy2) cyaw.extend(cyaw2) ck.extend(ck2) return cx, cy, cyaw, ck
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L531-L546
2
[ 0, 1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15 ]
87.5
[]
0
false
94.136808
16
2
100
0
def get_switch_back_course(dl): ax = [0.0, 30.0, 6.0, 20.0, 35.0] ay = [0.0, 0.0, 20.0, 35.0, 20.0] cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) ax = [35.0, 10.0, 0.0, 0.0] ay = [20.0, 30.0, 5.0, 0.0] cx2, cy2, cyaw2, ck2, s2 = cubic_spline_planner.calc_spline_course( ax, ay, ds=dl) cyaw2 = [i - math.pi for i in cyaw2] cx.extend(cx2) cy.extend(cy2) cyaw.extend(cyaw2) ck.extend(ck2) return cx, cy, cyaw, ck
698
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
main
()
549
583
def main(): print(__file__ + " start!!") dl = 1.0 # course tick # cx, cy, cyaw, ck = get_straight_course(dl) # cx, cy, cyaw, ck = get_straight_course2(dl) # cx, cy, cyaw, ck = get_straight_course3(dl) # cx, cy, cyaw, ck = get_forward_course(dl) cx, cy, cyaw, ck = get_switch_back_course(dl) sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED) initial_state = State(x=cx[0], y=cy[0], yaw=cyaw[0], v=0.0) t, x, y, yaw, v, d, a = do_simulation( cx, cy, cyaw, ck, sp, dl, initial_state) if show_animation: # pragma: no cover plt.close("all") plt.subplots() plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots() plt.plot(t, v, "-r", label="speed") plt.grid(True) plt.xlabel("Time [s]") plt.ylabel("Speed [kmh]") plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L549-L583
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
78.947368
[]
0
false
94.136808
35
2
100
0
def main(): print(__file__ + " start!!") dl = 1.0 # course tick # cx, cy, cyaw, ck = get_straight_course(dl) # cx, cy, cyaw, ck = get_straight_course2(dl) # cx, cy, cyaw, ck = get_straight_course3(dl) # cx, cy, cyaw, ck = get_forward_course(dl) cx, cy, cyaw, ck = get_switch_back_course(dl) sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED) initial_state = State(x=cx[0], y=cy[0], yaw=cyaw[0], v=0.0) t, x, y, yaw, v, d, a = do_simulation( cx, cy, cyaw, ck, sp, dl, initial_state) if show_animation: # pragma: no cover plt.close("all") plt.subplots() plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots() plt.plot(t, v, "-r", label="speed") plt.grid(True) plt.xlabel("Time [s]") plt.ylabel("Speed [kmh]") plt.show()
699
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
main2
()
586
616
def main2(): print(__file__ + " start!!") dl = 1.0 # course tick cx, cy, cyaw, ck = get_straight_course3(dl) sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED) initial_state = State(x=cx[0], y=cy[0], yaw=0.0, v=0.0) t, x, y, yaw, v, d, a = do_simulation( cx, cy, cyaw, ck, sp, dl, initial_state) if show_animation: # pragma: no cover plt.close("all") plt.subplots() plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots() plt.plot(t, v, "-r", label="speed") plt.grid(True) plt.xlabel("Time [s]") plt.ylabel("Speed [kmh]") plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L586-L616
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
73.333333
[]
0
false
94.136808
31
2
100
0
def main2(): print(__file__ + " start!!") dl = 1.0 # course tick cx, cy, cyaw, ck = get_straight_course3(dl) sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED) initial_state = State(x=cx[0], y=cy[0], yaw=0.0, v=0.0) t, x, y, yaw, v, d, a = do_simulation( cx, cy, cyaw, ck, sp, dl, initial_state) if show_animation: # pragma: no cover plt.close("all") plt.subplots() plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots() plt.plot(t, v, "-r", label="speed") plt.grid(True) plt.xlabel("Time [s]") plt.ylabel("Speed [kmh]") plt.show()
700
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0)
63
68
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v self.predelta = None
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/model_predictive_speed_and_steer_control/model_predictive_speed_and_steer_control.py#L63-L68
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
94.136808
6
1
100
0
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v self.predelta = None
701
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
calc_potential_field
(gx, gy, ox, oy, reso, rr, sx, sy)
return pmap, minx, miny
26
47
def calc_potential_field(gx, gy, ox, oy, reso, rr, sx, sy): minx = min(min(ox), sx, gx) - AREA_WIDTH / 2.0 miny = min(min(oy), sy, gy) - AREA_WIDTH / 2.0 maxx = max(max(ox), sx, gx) + AREA_WIDTH / 2.0 maxy = max(max(oy), sy, gy) + AREA_WIDTH / 2.0 xw = int(round((maxx - minx) / reso)) yw = int(round((maxy - miny) / reso)) # calc each potential pmap = [[0.0 for i in range(yw)] for i in range(xw)] for ix in range(xw): x = ix * reso + minx for iy in range(yw): y = iy * reso + miny ug = calc_attractive_potential(x, y, gx, gy) uo = calc_repulsive_potential(x, y, ox, oy, rr) uf = ug + uo pmap[ix][iy] = uf return pmap, minx, miny
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L26-L47
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
84.297521
22
5
100
0
def calc_potential_field(gx, gy, ox, oy, reso, rr, sx, sy): minx = min(min(ox), sx, gx) - AREA_WIDTH / 2.0 miny = min(min(oy), sy, gy) - AREA_WIDTH / 2.0 maxx = max(max(ox), sx, gx) + AREA_WIDTH / 2.0 maxy = max(max(oy), sy, gy) + AREA_WIDTH / 2.0 xw = int(round((maxx - minx) / reso)) yw = int(round((maxy - miny) / reso)) # calc each potential pmap = [[0.0 for i in range(yw)] for i in range(xw)] for ix in range(xw): x = ix * reso + minx for iy in range(yw): y = iy * reso + miny ug = calc_attractive_potential(x, y, gx, gy) uo = calc_repulsive_potential(x, y, ox, oy, rr) uf = ug + uo pmap[ix][iy] = uf return pmap, minx, miny
708
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
calc_attractive_potential
(x, y, gx, gy)
return 0.5 * KP * np.hypot(x - gx, y - gy)
50
51
def calc_attractive_potential(x, y, gx, gy): return 0.5 * KP * np.hypot(x - gx, y - gy)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L50-L51
2
[ 0, 1 ]
100
[]
0
true
84.297521
2
1
100
0
def calc_attractive_potential(x, y, gx, gy): return 0.5 * KP * np.hypot(x - gx, y - gy)
709
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
calc_repulsive_potential
(x, y, ox, oy, rr)
54
73
def calc_repulsive_potential(x, y, ox, oy, rr): # search nearest obstacle minid = -1 dmin = float("inf") for i, _ in enumerate(ox): d = np.hypot(x - ox[i], y - oy[i]) if dmin >= d: dmin = d minid = i # calc repulsive potential dq = np.hypot(x - ox[minid], y - oy[minid]) if dq <= rr: if dq <= 0.1: dq = 0.1 return 0.5 * ETA * (1.0 / dq - 1.0 / rr) ** 2 else: return 0.0
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L54-L73
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19 ]
95
[]
0
false
84.297521
20
5
100
0
def calc_repulsive_potential(x, y, ox, oy, rr): # search nearest obstacle minid = -1 dmin = float("inf") for i, _ in enumerate(ox): d = np.hypot(x - ox[i], y - oy[i]) if dmin >= d: dmin = d minid = i # calc repulsive potential dq = np.hypot(x - ox[minid], y - oy[minid]) if dq <= rr: if dq <= 0.1: dq = 0.1 return 0.5 * ETA * (1.0 / dq - 1.0 / rr) ** 2 else: return 0.0
710
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
get_motion_model
()
return motion
76
87
def get_motion_model(): # dx, dy motion = [[1, 0], [0, 1], [-1, 0], [0, -1], [-1, -1], [-1, 1], [1, -1], [1, 1]] return motion
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L76-L87
2
[ 0, 1, 2, 10, 11 ]
41.666667
[]
0
false
84.297521
12
1
100
0
def get_motion_model(): # dx, dy motion = [[1, 0], [0, 1], [-1, 0], [0, -1], [-1, -1], [-1, 1], [1, -1], [1, 1]] return motion
711
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
oscillations_detection
(previous_ids, ix, iy)
return False
90
103
def oscillations_detection(previous_ids, ix, iy): previous_ids.append((ix, iy)) if (len(previous_ids) > OSCILLATIONS_DETECTION_LENGTH): previous_ids.popleft() # check if contains any duplicates by copying into a set previous_ids_set = set() for index in previous_ids: if index in previous_ids_set: return True else: previous_ids_set.add(index) return False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L90-L103
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13 ]
85.714286
[ 10 ]
7.142857
false
84.297521
14
4
92.857143
0
def oscillations_detection(previous_ids, ix, iy): previous_ids.append((ix, iy)) if (len(previous_ids) > OSCILLATIONS_DETECTION_LENGTH): previous_ids.popleft() # check if contains any duplicates by copying into a set previous_ids_set = set() for index in previous_ids: if index in previous_ids_set: return True else: previous_ids_set.add(index) return False
712
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
potential_field_planning
(sx, sy, gx, gy, ox, oy, reso, rr)
return rx, ry
106
163
def potential_field_planning(sx, sy, gx, gy, ox, oy, reso, rr): # calc potential field pmap, minx, miny = calc_potential_field(gx, gy, ox, oy, reso, rr, sx, sy) # search path d = np.hypot(sx - gx, sy - gy) ix = round((sx - minx) / reso) iy = round((sy - miny) / reso) gix = round((gx - minx) / reso) giy = round((gy - miny) / reso) if show_animation: draw_heatmap(pmap) # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(ix, iy, "*k") plt.plot(gix, giy, "*m") rx, ry = [sx], [sy] motion = get_motion_model() previous_ids = deque() while d >= reso: minp = float("inf") minix, miniy = -1, -1 for i, _ in enumerate(motion): inx = int(ix + motion[i][0]) iny = int(iy + motion[i][1]) if inx >= len(pmap) or iny >= len(pmap[0]) or inx < 0 or iny < 0: p = float("inf") # outside area print("outside potential!") else: p = pmap[inx][iny] if minp > p: minp = p minix = inx miniy = iny ix = minix iy = miniy xp = ix * reso + minx yp = iy * reso + miny d = np.hypot(gx - xp, gy - yp) rx.append(xp) ry.append(yp) if (oscillations_detection(previous_ids, ix, iy)): print("Oscillation detected at ({},{})!".format(ix, iy)) break if show_animation: plt.plot(ix, iy, ".r") plt.pause(0.01) print("Goal!!") return rx, ry
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L106-L163
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 50, 51, 54, 55, 56, 57 ]
77.586207
[ 13, 15, 17, 18, 31, 32, 48, 49, 52, 53 ]
17.241379
false
84.297521
58
11
82.758621
0
def potential_field_planning(sx, sy, gx, gy, ox, oy, reso, rr): # calc potential field pmap, minx, miny = calc_potential_field(gx, gy, ox, oy, reso, rr, sx, sy) # search path d = np.hypot(sx - gx, sy - gy) ix = round((sx - minx) / reso) iy = round((sy - miny) / reso) gix = round((gx - minx) / reso) giy = round((gy - miny) / reso) if show_animation: draw_heatmap(pmap) # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(ix, iy, "*k") plt.plot(gix, giy, "*m") rx, ry = [sx], [sy] motion = get_motion_model() previous_ids = deque() while d >= reso: minp = float("inf") minix, miniy = -1, -1 for i, _ in enumerate(motion): inx = int(ix + motion[i][0]) iny = int(iy + motion[i][1]) if inx >= len(pmap) or iny >= len(pmap[0]) or inx < 0 or iny < 0: p = float("inf") # outside area print("outside potential!") else: p = pmap[inx][iny] if minp > p: minp = p minix = inx miniy = iny ix = minix iy = miniy xp = ix * reso + minx yp = iy * reso + miny d = np.hypot(gx - xp, gy - yp) rx.append(xp) ry.append(yp) if (oscillations_detection(previous_ids, ix, iy)): print("Oscillation detected at ({},{})!".format(ix, iy)) break if show_animation: plt.plot(ix, iy, ".r") plt.pause(0.01) print("Goal!!") return rx, ry
713
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
draw_heatmap
(data)
166
168
def draw_heatmap(data): data = np.array(data).T plt.pcolor(data, vmax=100.0, cmap=plt.cm.Blues)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L166-L168
2
[ 0 ]
33.333333
[ 1, 2 ]
66.666667
false
84.297521
3
1
33.333333
0
def draw_heatmap(data): data = np.array(data).T plt.pcolor(data, vmax=100.0, cmap=plt.cm.Blues)
714
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/PotentialFieldPlanning/potential_field_planning.py
main
()
171
193
def main(): print("potential_field_planning start") sx = 0.0 # start x position [m] sy = 10.0 # start y positon [m] gx = 30.0 # goal x position [m] gy = 30.0 # goal y position [m] grid_size = 0.5 # potential grid size [m] robot_radius = 5.0 # robot radius [m] ox = [15.0, 5.0, 20.0, 25.0] # obstacle x position list [m] oy = [25.0, 15.0, 26.0, 25.0] # obstacle y position list [m] if show_animation: plt.grid(True) plt.axis("equal") # path generation _, _ = potential_field_planning( sx, sy, gx, gy, ox, oy, grid_size, robot_radius) if show_animation: plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/PotentialFieldPlanning/potential_field_planning.py#L171-L193
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 18, 20, 21 ]
78.26087
[ 14, 15, 22 ]
13.043478
false
84.297521
23
3
86.956522
0
def main(): print("potential_field_planning start") sx = 0.0 # start x position [m] sy = 10.0 # start y positon [m] gx = 30.0 # goal x position [m] gy = 30.0 # goal y position [m] grid_size = 0.5 # potential grid size [m] robot_radius = 5.0 # robot radius [m] ox = [15.0, 5.0, 20.0, 25.0] # obstacle x position list [m] oy = [25.0, 15.0, 26.0, 25.0] # obstacle y position list [m] if show_animation: plt.grid(True) plt.axis("equal") # path generation _, _ = potential_field_planning( sx, sy, gx, gy, ox, oy, grid_size, robot_radius) if show_animation: plt.show()
715
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
add_coordinates
(node1: Node, node2: Node)
return new_node
29
34
def add_coordinates(node1: Node, node2: Node): new_node = Node() new_node.x = node1.x + node2.x new_node.y = node1.y + node2.y new_node.cost = node1.cost + node2.cost return new_node
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L29-L34
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
74.621212
6
1
100
0
def add_coordinates(node1: Node, node2: Node): new_node = Node() new_node.x = node1.x + node2.x new_node.y = node1.y + node2.y new_node.cost = node1.cost + node2.cost return new_node
716
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
compare_coordinates
(node1: Node, node2: Node)
return node1.x == node2.x and node1.y == node2.y
37
38
def compare_coordinates(node1: Node, node2: Node): return node1.x == node2.x and node1.y == node2.y
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L37-L38
2
[ 0, 1 ]
100
[]
0
true
74.621212
2
2
100
0
def compare_coordinates(node1: Node, node2: Node): return node1.x == node2.x and node1.y == node2.y
717
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
main
()
353
423
def main(): # start and goal position sx = 10 # [m] sy = 10 # [m] gx = 50 # [m] gy = 50 # [m] # set obstacle positions ox, oy = [], [] for i in range(-10, 60): ox.append(i) oy.append(-10.0) for i in range(-10, 60): ox.append(60.0) oy.append(i) for i in range(-10, 61): ox.append(i) oy.append(60.0) for i in range(-10, 61): ox.append(-10.0) oy.append(i) for i in range(-10, 40): ox.append(20.0) oy.append(i) for i in range(0, 40): ox.append(40.0) oy.append(60.0 - i) if show_animation: plt.plot(ox, oy, ".k") plt.plot(sx, sy, "og") plt.plot(gx, gy, "xb") plt.grid(True) plt.axis("equal") label_column = ['Start', 'Goal', 'Path taken', 'Current computed path', 'Previous computed path', 'Obstacles'] columns = [plt.plot([], [], symbol, color=colour, alpha=alpha)[0] for symbol, colour, alpha in [['o', 'g', 1], ['x', 'b', 1], ['-', 'r', 1], ['.', 'c', 1], ['.', 'c', 0.3], ['.', 'k', 1]]] plt.legend(columns, label_column, bbox_to_anchor=(1, 1), title="Key:", fontsize="xx-small") plt.plot() plt.pause(pause_time) # Obstacles discovered at time = row # time = 1, obstacles discovered at (0, 2), (9, 2), (4, 0) # time = 2, obstacles discovered at (0, 1), (7, 7) # ... # when the spoofed obstacles are: # spoofed_ox = [[0, 9, 4], [0, 7], [], [], [], [], [], [5]] # spoofed_oy = [[2, 2, 0], [1, 7], [], [], [], [], [], [4]] # Reroute # spoofed_ox = [[], [], [], [], [], [], [], [40 for _ in range(10, 21)]] # spoofed_oy = [[], [], [], [], [], [], [], [i for i in range(10, 21)]] # Obstacles that demostrate large rerouting spoofed_ox = [[], [], [], [i for i in range(0, 21)] + [0 for _ in range(0, 20)]] spoofed_oy = [[], [], [], [20 for _ in range(0, 21)] + [i for i in range(0, 20)]] dstarlite = DStarLite(ox, oy) dstarlite.main(Node(x=sx, y=sy), Node(x=gx, y=gy), spoofed_ox=spoofed_ox, spoofed_oy=spoofed_oy)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L353-L423
2
[ 0, 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, 62, 63, 65, 67, 68, 69 ]
50.704225
[ 30, 31, 32, 33, 34, 35, 38, 45, 47, 48 ]
14.084507
false
74.621212
71
13
85.915493
0
def main(): # start and goal position sx = 10 # [m] sy = 10 # [m] gx = 50 # [m] gy = 50 # [m] # set obstacle positions ox, oy = [], [] for i in range(-10, 60): ox.append(i) oy.append(-10.0) for i in range(-10, 60): ox.append(60.0) oy.append(i) for i in range(-10, 61): ox.append(i) oy.append(60.0) for i in range(-10, 61): ox.append(-10.0) oy.append(i) for i in range(-10, 40): ox.append(20.0) oy.append(i) for i in range(0, 40): ox.append(40.0) oy.append(60.0 - i) if show_animation: plt.plot(ox, oy, ".k") plt.plot(sx, sy, "og") plt.plot(gx, gy, "xb") plt.grid(True) plt.axis("equal") label_column = ['Start', 'Goal', 'Path taken', 'Current computed path', 'Previous computed path', 'Obstacles'] columns = [plt.plot([], [], symbol, color=colour, alpha=alpha)[0] for symbol, colour, alpha in [['o', 'g', 1], ['x', 'b', 1], ['-', 'r', 1], ['.', 'c', 1], ['.', 'c', 0.3], ['.', 'k', 1]]] plt.legend(columns, label_column, bbox_to_anchor=(1, 1), title="Key:", fontsize="xx-small") plt.plot() plt.pause(pause_time) # Obstacles discovered at time = row # time = 1, obstacles discovered at (0, 2), (9, 2), (4, 0) # time = 2, obstacles discovered at (0, 1), (7, 7) # ... # when the spoofed obstacles are: # spoofed_ox = [[0, 9, 4], [0, 7], [], [], [], [], [], [5]] # spoofed_oy = [[2, 2, 0], [1, 7], [], [], [], [], [], [4]] # Reroute # spoofed_ox = [[], [], [], [], [], [], [], [40 for _ in range(10, 21)]] # spoofed_oy = [[], [], [], [], [], [], [], [i for i in range(10, 21)]] # Obstacles that demostrate large rerouting spoofed_ox = [[], [], [], [i for i in range(0, 21)] + [0 for _ in range(0, 20)]] spoofed_oy = [[], [], [], [20 for _ in range(0, 21)] + [i for i in range(0, 20)]] dstarlite = DStarLite(ox, oy) dstarlite.main(Node(x=sx, y=sy), Node(x=gx, y=gy), spoofed_ox=spoofed_ox, spoofed_oy=spoofed_oy)
718
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
Node.__init__
(self, x: int = 0, y: int = 0, cost: float = 0.0)
23
26
def __init__(self, x: int = 0, y: int = 0, cost: float = 0.0): self.x = x self.y = y self.cost = cost
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L23-L26
2
[ 0, 1, 2, 3 ]
100
[]
0
true
74.621212
4
1
100
0
def __init__(self, x: int = 0, y: int = 0, cost: float = 0.0): self.x = x self.y = y self.cost = cost
719
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.__init__
(self, ox: list, oy: list)
56
81
def __init__(self, ox: list, oy: list): # Ensure that within the algorithm implementation all node coordinates # are indices in the grid and extend # from 0 to abs(<axis>_max - <axis>_min) self.x_min_world = int(min(ox)) self.y_min_world = int(min(oy)) self.x_max = int(abs(max(ox) - self.x_min_world)) self.y_max = int(abs(max(oy) - self.y_min_world)) self.obstacles = [Node(x - self.x_min_world, y - self.y_min_world) for x, y in zip(ox, oy)] self.obstacles_xy = np.array( [[obstacle.x, obstacle.y] for obstacle in self.obstacles] ) self.start = Node(0, 0) self.goal = Node(0, 0) self.U = list() # type: ignore self.km = 0.0 self.kold = 0.0 self.rhs = self.create_grid(float("inf")) self.g = self.create_grid(float("inf")) self.detected_obstacles_xy = np.empty((0, 2)) self.xy = np.empty((0, 2)) if show_animation: self.detected_obstacles_for_plotting_x = list() # type: ignore self.detected_obstacles_for_plotting_y = list() # type: ignore self.initialized = False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L56-L81
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25 ]
80.769231
[ 23, 24 ]
7.692308
false
74.621212
26
4
92.307692
0
def __init__(self, ox: list, oy: list): # Ensure that within the algorithm implementation all node coordinates # are indices in the grid and extend # from 0 to abs(<axis>_max - <axis>_min) self.x_min_world = int(min(ox)) self.y_min_world = int(min(oy)) self.x_max = int(abs(max(ox) - self.x_min_world)) self.y_max = int(abs(max(oy) - self.y_min_world)) self.obstacles = [Node(x - self.x_min_world, y - self.y_min_world) for x, y in zip(ox, oy)] self.obstacles_xy = np.array( [[obstacle.x, obstacle.y] for obstacle in self.obstacles] ) self.start = Node(0, 0) self.goal = Node(0, 0) self.U = list() # type: ignore self.km = 0.0 self.kold = 0.0 self.rhs = self.create_grid(float("inf")) self.g = self.create_grid(float("inf")) self.detected_obstacles_xy = np.empty((0, 2)) self.xy = np.empty((0, 2)) if show_animation: self.detected_obstacles_for_plotting_x = list() # type: ignore self.detected_obstacles_for_plotting_y = list() # type: ignore self.initialized = False
720
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.create_grid
(self, val: float)
return np.full((self.x_max, self.y_max), val)
83
84
def create_grid(self, val: float): return np.full((self.x_max, self.y_max), val)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L83-L84
2
[ 0, 1 ]
100
[]
0
true
74.621212
2
1
100
0
def create_grid(self, val: float): return np.full((self.x_max, self.y_max), val)
721
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.is_obstacle
(self, node: Node)
return is_in_obstacles or is_in_detected_obstacles
86
99
def is_obstacle(self, node: Node): x = np.array([node.x]) y = np.array([node.y]) obstacle_x_equal = self.obstacles_xy[:, 0] == x obstacle_y_equal = self.obstacles_xy[:, 1] == y is_in_obstacles = (obstacle_x_equal & obstacle_y_equal).any() is_in_detected_obstacles = False if self.detected_obstacles_xy.shape[0] > 0: is_x_equal = self.detected_obstacles_xy[:, 0] == x is_y_equal = self.detected_obstacles_xy[:, 1] == y is_in_detected_obstacles = (is_x_equal & is_y_equal).any() return is_in_obstacles or is_in_detected_obstacles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L86-L99
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
74.621212
14
3
100
0
def is_obstacle(self, node: Node): x = np.array([node.x]) y = np.array([node.y]) obstacle_x_equal = self.obstacles_xy[:, 0] == x obstacle_y_equal = self.obstacles_xy[:, 1] == y is_in_obstacles = (obstacle_x_equal & obstacle_y_equal).any() is_in_detected_obstacles = False if self.detected_obstacles_xy.shape[0] > 0: is_x_equal = self.detected_obstacles_xy[:, 0] == x is_y_equal = self.detected_obstacles_xy[:, 1] == y is_in_detected_obstacles = (is_x_equal & is_y_equal).any() return is_in_obstacles or is_in_detected_obstacles
722
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.c
(self, node1: Node, node2: Node)
return detected_motion[0].cost
101
109
def c(self, node1: Node, node2: Node): if self.is_obstacle(node2): # Attempting to move from or to an obstacle return math.inf new_node = Node(node1.x-node2.x, node1.y-node2.y) detected_motion = list(filter(lambda motion: compare_coordinates(motion, new_node), self.motions)) return detected_motion[0].cost
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L101-L109
2
[ 0, 1, 2, 3, 4, 5, 8 ]
77.777778
[]
0
false
74.621212
9
2
100
0
def c(self, node1: Node, node2: Node): if self.is_obstacle(node2): # Attempting to move from or to an obstacle return math.inf new_node = Node(node1.x-node2.x, node1.y-node2.y) detected_motion = list(filter(lambda motion: compare_coordinates(motion, new_node), self.motions)) return detected_motion[0].cost
723
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.h
(self, s: Node)
return 1
111
123
def h(self, s: Node): # Cannot use the 2nd euclidean norm as this might sometimes generate # heuristics that overestimate the cost, making them inadmissible, # due to rounding errors etc (when combined with calculate_key) # To be admissible heuristic should # never overestimate the cost of a move # hence not using the line below # return math.hypot(self.start.x - s.x, self.start.y - s.y) # Below is the same as 1; modify if you modify the cost of each move in # motion # return max(abs(self.start.x - s.x), abs(self.start.y - s.y)) return 1
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L111-L123
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
74.621212
13
1
100
0
def h(self, s: Node): # Cannot use the 2nd euclidean norm as this might sometimes generate # heuristics that overestimate the cost, making them inadmissible, # due to rounding errors etc (when combined with calculate_key) # To be admissible heuristic should # never overestimate the cost of a move # hence not using the line below # return math.hypot(self.start.x - s.x, self.start.y - s.y) # Below is the same as 1; modify if you modify the cost of each move in # motion # return max(abs(self.start.x - s.x), abs(self.start.y - s.y)) return 1
724
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.calculate_key
(self, s: Node)
return (min(self.g[s.x][s.y], self.rhs[s.x][s.y]) + self.h(s) + self.km, min(self.g[s.x][s.y], self.rhs[s.x][s.y]))
125
127
def calculate_key(self, s: Node): return (min(self.g[s.x][s.y], self.rhs[s.x][s.y]) + self.h(s) + self.km, min(self.g[s.x][s.y], self.rhs[s.x][s.y]))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L125-L127
2
[ 0, 1 ]
66.666667
[]
0
false
74.621212
3
1
100
0
def calculate_key(self, s: Node): return (min(self.g[s.x][s.y], self.rhs[s.x][s.y]) + self.h(s) + self.km, min(self.g[s.x][s.y], self.rhs[s.x][s.y]))
725
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.is_valid
(self, node: Node)
return False
129
132
def is_valid(self, node: Node): if 0 <= node.x < self.x_max and 0 <= node.y < self.y_max: return True return False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L129-L132
2
[ 0, 1, 2, 3 ]
100
[]
0
true
74.621212
4
3
100
0
def is_valid(self, node: Node): if 0 <= node.x < self.x_max and 0 <= node.y < self.y_max: return True return False
726
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.get_neighbours
(self, u: Node)
return [add_coordinates(u, motion) for motion in self.motions if self.is_valid(add_coordinates(u, motion))]
134
136
def get_neighbours(self, u: Node): return [add_coordinates(u, motion) for motion in self.motions if self.is_valid(add_coordinates(u, motion))]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L134-L136
2
[ 0, 1 ]
66.666667
[]
0
false
74.621212
3
2
100
0
def get_neighbours(self, u: Node): return [add_coordinates(u, motion) for motion in self.motions if self.is_valid(add_coordinates(u, motion))]
727
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.pred
(self, u: Node)
return self.get_neighbours(u)
138
140
def pred(self, u: Node): # Grid, so each vertex is connected to the ones around it return self.get_neighbours(u)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L138-L140
2
[ 0, 1, 2 ]
100
[]
0
true
74.621212
3
1
100
0
def pred(self, u: Node): # Grid, so each vertex is connected to the ones around it return self.get_neighbours(u)
728
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.succ
(self, u: Node)
return self.get_neighbours(u)
142
144
def succ(self, u: Node): # Grid, so each vertex is connected to the ones around it return self.get_neighbours(u)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L142-L144
2
[ 0, 1, 2 ]
100
[]
0
true
74.621212
3
1
100
0
def succ(self, u: Node): # Grid, so each vertex is connected to the ones around it return self.get_neighbours(u)
729
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.initialize
(self, start: Node, goal: Node)
146
160
def initialize(self, start: Node, goal: Node): self.start.x = start.x - self.x_min_world self.start.y = start.y - self.y_min_world self.goal.x = goal.x - self.x_min_world self.goal.y = goal.y - self.y_min_world if not self.initialized: self.initialized = True print('Initializing') self.U = list() # Would normally be a priority queue self.km = 0.0 self.rhs = self.create_grid(math.inf) self.g = self.create_grid(math.inf) self.rhs[self.goal.x][self.goal.y] = 0 self.U.append((self.goal, self.calculate_key(self.goal))) self.detected_obstacles_xy = np.empty((0, 2))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L146-L160
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
74.621212
15
2
100
0
def initialize(self, start: Node, goal: Node): self.start.x = start.x - self.x_min_world self.start.y = start.y - self.y_min_world self.goal.x = goal.x - self.x_min_world self.goal.y = goal.y - self.y_min_world if not self.initialized: self.initialized = True print('Initializing') self.U = list() # Would normally be a priority queue self.km = 0.0 self.rhs = self.create_grid(math.inf) self.g = self.create_grid(math.inf) self.rhs[self.goal.x][self.goal.y] = 0 self.U.append((self.goal, self.calculate_key(self.goal))) self.detected_obstacles_xy = np.empty((0, 2))
730
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.update_vertex
(self, u: Node)
162
173
def update_vertex(self, u: Node): if not compare_coordinates(u, self.goal): self.rhs[u.x][u.y] = min([self.c(u, sprime) + self.g[sprime.x][sprime.y] for sprime in self.succ(u)]) if any([compare_coordinates(u, node) for node, key in self.U]): self.U = [(node, key) for node, key in self.U if not compare_coordinates(node, u)] self.U.sort(key=lambda x: x[1]) if self.g[u.x][u.y] != self.rhs[u.x][u.y]: self.U.append((u, self.calculate_key(u))) self.U.sort(key=lambda x: x[1])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L162-L173
2
[ 0, 1, 2, 5, 6, 8, 9, 10, 11 ]
75
[]
0
false
74.621212
12
7
100
0
def update_vertex(self, u: Node): if not compare_coordinates(u, self.goal): self.rhs[u.x][u.y] = min([self.c(u, sprime) + self.g[sprime.x][sprime.y] for sprime in self.succ(u)]) if any([compare_coordinates(u, node) for node, key in self.U]): self.U = [(node, key) for node, key in self.U if not compare_coordinates(node, u)] self.U.sort(key=lambda x: x[1]) if self.g[u.x][u.y] != self.rhs[u.x][u.y]: self.U.append((u, self.calculate_key(u))) self.U.sort(key=lambda x: x[1])
731
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.compare_keys
(self, key_pair1: tuple[float, float], key_pair2: tuple[float, float])
return key_pair1[0] < key_pair2[0] or \ (key_pair1[0] == key_pair2[0] and key_pair1[1] < key_pair2[1])
175
178
def compare_keys(self, key_pair1: tuple[float, float], key_pair2: tuple[float, float]): return key_pair1[0] < key_pair2[0] or \ (key_pair1[0] == key_pair2[0] and key_pair1[1] < key_pair2[1])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L175-L178
2
[ 0, 2 ]
50
[]
0
false
74.621212
4
3
100
0
def compare_keys(self, key_pair1: tuple[float, float], key_pair2: tuple[float, float]): return key_pair1[0] < key_pair2[0] or \ (key_pair1[0] == key_pair2[0] and key_pair1[1] < key_pair2[1])
732
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.detect_changes
(self)
return changed_vertices
210
258
def detect_changes(self): changed_vertices = list() if len(self.spoofed_obstacles) > 0: for spoofed_obstacle in self.spoofed_obstacles[0]: if compare_coordinates(spoofed_obstacle, self.start) or \ compare_coordinates(spoofed_obstacle, self.goal): continue changed_vertices.append(spoofed_obstacle) self.detected_obstacles_xy = np.concatenate( ( self.detected_obstacles_xy, [[spoofed_obstacle.x, spoofed_obstacle.y]] ) ) if show_animation: self.detected_obstacles_for_plotting_x.append( spoofed_obstacle.x + self.x_min_world) self.detected_obstacles_for_plotting_y.append( spoofed_obstacle.y + self.y_min_world) plt.plot(self.detected_obstacles_for_plotting_x, self.detected_obstacles_for_plotting_y, ".k") plt.pause(pause_time) self.spoofed_obstacles.pop(0) # Allows random generation of obstacles random.seed() if random.random() > 1 - p_create_random_obstacle: x = random.randint(0, self.x_max - 1) y = random.randint(0, self.y_max - 1) new_obs = Node(x, y) if compare_coordinates(new_obs, self.start) or \ compare_coordinates(new_obs, self.goal): return changed_vertices changed_vertices.append(Node(x, y)) self.detected_obstacles_xy = np.concatenate( ( self.detected_obstacles_xy, [[x, y]] ) ) if show_animation: self.detected_obstacles_for_plotting_x.append(x + self.x_min_world) self.detected_obstacles_for_plotting_y.append(y + self.y_min_world) plt.plot(self.detected_obstacles_for_plotting_x, self.detected_obstacles_for_plotting_y, ".k") plt.pause(pause_time) return changed_vertices
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L210-L258
2
[ 0, 1, 2, 3, 4, 7, 8, 14, 22, 23, 24, 25, 26, 48 ]
28.571429
[ 6, 15, 17, 19, 21, 27, 28, 29, 30, 32, 33, 34, 40, 41, 43, 45, 47 ]
34.693878
false
74.621212
49
10
65.306122
0
def detect_changes(self): changed_vertices = list() if len(self.spoofed_obstacles) > 0: for spoofed_obstacle in self.spoofed_obstacles[0]: if compare_coordinates(spoofed_obstacle, self.start) or \ compare_coordinates(spoofed_obstacle, self.goal): continue changed_vertices.append(spoofed_obstacle) self.detected_obstacles_xy = np.concatenate( ( self.detected_obstacles_xy, [[spoofed_obstacle.x, spoofed_obstacle.y]] ) ) if show_animation: self.detected_obstacles_for_plotting_x.append( spoofed_obstacle.x + self.x_min_world) self.detected_obstacles_for_plotting_y.append( spoofed_obstacle.y + self.y_min_world) plt.plot(self.detected_obstacles_for_plotting_x, self.detected_obstacles_for_plotting_y, ".k") plt.pause(pause_time) self.spoofed_obstacles.pop(0) # Allows random generation of obstacles random.seed() if random.random() > 1 - p_create_random_obstacle: x = random.randint(0, self.x_max - 1) y = random.randint(0, self.y_max - 1) new_obs = Node(x, y) if compare_coordinates(new_obs, self.start) or \ compare_coordinates(new_obs, self.goal): return changed_vertices changed_vertices.append(Node(x, y)) self.detected_obstacles_xy = np.concatenate( ( self.detected_obstacles_xy, [[x, y]] ) ) if show_animation: self.detected_obstacles_for_plotting_x.append(x + self.x_min_world) self.detected_obstacles_for_plotting_y.append(y + self.y_min_world) plt.plot(self.detected_obstacles_for_plotting_x, self.detected_obstacles_for_plotting_y, ".k") plt.pause(pause_time) return changed_vertices
733
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.compute_current_path
(self)
return path
260
270
def compute_current_path(self): path = list() current_point = Node(self.start.x, self.start.y) while not compare_coordinates(current_point, self.goal): path.append(current_point) current_point = min(self.succ(current_point), key=lambda sprime: self.c(current_point, sprime) + self.g[sprime.x][sprime.y]) path.append(self.goal) return path
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L260-L270
2
[ 0 ]
9.090909
[ 1, 2, 3, 4, 5, 9, 10 ]
63.636364
false
74.621212
11
2
36.363636
0
def compute_current_path(self): path = list() current_point = Node(self.start.x, self.start.y) while not compare_coordinates(current_point, self.goal): path.append(current_point) current_point = min(self.succ(current_point), key=lambda sprime: self.c(current_point, sprime) + self.g[sprime.x][sprime.y]) path.append(self.goal) return path
734
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.compare_paths
(self, path1: list, path2: list)
return True
272
278
def compare_paths(self, path1: list, path2: list): if len(path1) != len(path2): return False for node1, node2 in zip(path1, path2): if not compare_coordinates(node1, node2): return False return True
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L272-L278
2
[ 0 ]
14.285714
[ 1, 2, 3, 4, 5, 6 ]
85.714286
false
74.621212
7
4
14.285714
0
def compare_paths(self, path1: list, path2: list): if len(path1) != len(path2): return False for node1, node2 in zip(path1, path2): if not compare_coordinates(node1, node2): return False return True
735
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.display_path
(self, path: list, colour: str, alpha: float = 1.0)
return drawing
280
285
def display_path(self, path: list, colour: str, alpha: float = 1.0): px = [(node.x + self.x_min_world) for node in path] py = [(node.y + self.y_min_world) for node in path] drawing = plt.plot(px, py, colour, alpha=alpha) plt.pause(pause_time) return drawing
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L280-L285
2
[ 0 ]
16.666667
[ 1, 2, 3, 4, 5 ]
83.333333
false
74.621212
6
3
16.666667
0
def display_path(self, path: list, colour: str, alpha: float = 1.0): px = [(node.x + self.x_min_world) for node in path] py = [(node.y + self.y_min_world) for node in path] drawing = plt.plot(px, py, colour, alpha=alpha) plt.pause(pause_time) return drawing
736
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/DStarLite/d_star_lite.py
DStarLite.main
(self, start: Node, goal: Node, spoofed_ox: list, spoofed_oy: list)
return True, pathx, pathy
287
350
def main(self, start: Node, goal: Node, spoofed_ox: list, spoofed_oy: list): self.spoofed_obstacles = [[Node(x - self.x_min_world, y - self.y_min_world) for x, y in zip(rowx, rowy)] for rowx, rowy in zip(spoofed_ox, spoofed_oy) ] pathx = [] pathy = [] self.initialize(start, goal) last = self.start self.compute_shortest_path() pathx.append(self.start.x + self.x_min_world) pathy.append(self.start.y + self.y_min_world) if show_animation: current_path = self.compute_current_path() previous_path = current_path.copy() previous_path_image = self.display_path(previous_path, ".c", alpha=0.3) current_path_image = self.display_path(current_path, ".c") while not compare_coordinates(self.goal, self.start): if self.g[self.start.x][self.start.y] == math.inf: print("No path possible") return False, pathx, pathy self.start = min(self.succ(self.start), key=lambda sprime: self.c(self.start, sprime) + self.g[sprime.x][sprime.y]) pathx.append(self.start.x + self.x_min_world) pathy.append(self.start.y + self.y_min_world) if show_animation: current_path.pop(0) plt.plot(pathx, pathy, "-r") plt.pause(pause_time) changed_vertices = self.detect_changes() if len(changed_vertices) != 0: print("New obstacle detected") self.km += self.h(last) last = self.start for u in changed_vertices: if compare_coordinates(u, self.start): continue self.rhs[u.x][u.y] = math.inf self.g[u.x][u.y] = math.inf self.update_vertex(u) self.compute_shortest_path() if show_animation: new_path = self.compute_current_path() if not self.compare_paths(current_path, new_path): current_path_image[0].remove() previous_path_image[0].remove() previous_path = current_path.copy() current_path = new_path.copy() previous_path_image = self.display_path(previous_path, ".c", alpha=0.3) current_path_image = self.display_path(current_path, ".c") plt.pause(pause_time) print("Path found") return True, pathx, pathy
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/DStarLite/d_star_lite.py#L287-L350
2
[ 0, 2, 7, 8, 9, 10, 11, 12, 13, 14, 15, 21, 22, 23, 26, 30, 31, 32, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 62, 63 ]
51.5625
[ 16, 17, 18, 20, 24, 25, 33, 34, 35, 43, 50, 51, 52, 53, 54, 55, 56, 59, 61 ]
29.6875
false
74.621212
64
12
70.3125
0
def main(self, start: Node, goal: Node, spoofed_ox: list, spoofed_oy: list): self.spoofed_obstacles = [[Node(x - self.x_min_world, y - self.y_min_world) for x, y in zip(rowx, rowy)] for rowx, rowy in zip(spoofed_ox, spoofed_oy) ] pathx = [] pathy = [] self.initialize(start, goal) last = self.start self.compute_shortest_path() pathx.append(self.start.x + self.x_min_world) pathy.append(self.start.y + self.y_min_world) if show_animation: current_path = self.compute_current_path() previous_path = current_path.copy() previous_path_image = self.display_path(previous_path, ".c", alpha=0.3) current_path_image = self.display_path(current_path, ".c") while not compare_coordinates(self.goal, self.start): if self.g[self.start.x][self.start.y] == math.inf: print("No path possible") return False, pathx, pathy self.start = min(self.succ(self.start), key=lambda sprime: self.c(self.start, sprime) + self.g[sprime.x][sprime.y]) pathx.append(self.start.x + self.x_min_world) pathy.append(self.start.y + self.y_min_world) if show_animation: current_path.pop(0) plt.plot(pathx, pathy, "-r") plt.pause(pause_time) changed_vertices = self.detect_changes() if len(changed_vertices) != 0: print("New obstacle detected") self.km += self.h(last) last = self.start for u in changed_vertices: if compare_coordinates(u, self.start): continue self.rhs[u.x][u.y] = math.inf self.g[u.x][u.y] = math.inf self.update_vertex(u) self.compute_shortest_path() if show_animation: new_path = self.compute_current_path() if not self.compare_paths(current_path, new_path): current_path_image[0].remove() previous_path_image[0].remove() previous_path = current_path.copy() current_path = new_path.copy() previous_path_image = self.display_path(previous_path, ".c", alpha=0.3) current_path_image = self.display_path(current_path, ".c") plt.pause(pause_time) print("Path found") return True, pathx, pathy
737
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
draw_horizontal_line
(start_x, start_y, length, o_x, o_y, o_dict, path)
13
18
def draw_horizontal_line(start_x, start_y, length, o_x, o_y, o_dict, path): for i in range(start_x, start_x + length): for j in range(start_y, start_y + 2): o_x.append(i) o_y.append(j) o_dict[(i, j)] = path
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L13-L18
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.377483
6
3
100
0
def draw_horizontal_line(start_x, start_y, length, o_x, o_y, o_dict, path): for i in range(start_x, start_x + length): for j in range(start_y, start_y + 2): o_x.append(i) o_y.append(j) o_dict[(i, j)] = path
749
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
draw_vertical_line
(start_x, start_y, length, o_x, o_y, o_dict, path)
21
26
def draw_vertical_line(start_x, start_y, length, o_x, o_y, o_dict, path): for i in range(start_x, start_x + 2): for j in range(start_y, start_y + length): o_x.append(i) o_y.append(j) o_dict[(i, j)] = path
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L21-L26
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.377483
6
3
100
0
def draw_vertical_line(start_x, start_y, length, o_x, o_y, o_dict, path): for i in range(start_x, start_x + 2): for j in range(start_y, start_y + length): o_x.append(i) o_y.append(j) o_dict[(i, j)] = path
750
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
main
()
142
223
def main(): # set obstacle positions obs_dict = {} for i in range(51): for j in range(51): obs_dict[(i, j)] = 'free' o_x, o_y, m_x, m_y, h_x, h_y = [], [], [], [], [], [] s_x = 5.0 s_y = 5.0 g_x = 35.0 g_y = 45.0 # draw outer border of maze draw_vertical_line(0, 0, 50, o_x, o_y, obs_dict, 'obs') draw_vertical_line(48, 0, 50, o_x, o_y, obs_dict, 'obs') draw_horizontal_line(0, 0, 50, o_x, o_y, obs_dict, 'obs') draw_horizontal_line(0, 48, 50, o_x, o_y, obs_dict, 'obs') # draw inner walls all_x = [10, 10, 10, 15, 20, 20, 30, 30, 35, 30, 40, 45] all_y = [10, 30, 45, 20, 5, 40, 10, 40, 5, 40, 10, 25] all_len = [10, 10, 5, 10, 10, 5, 20, 10, 25, 10, 35, 15] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, o_x, o_y, obs_dict, 'obs') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [35, 40, 15, 10, 45, 20, 10, 15, 25, 45, 10, 30, 10, 40] all_y = [5, 10, 15, 20, 20, 25, 30, 35, 35, 35, 40, 40, 45, 45] all_len = [10, 5, 10, 10, 5, 5, 10, 5, 10, 5, 10, 5, 5, 5] for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, o_x, o_y, obs_dict, 'obs') # Some points are assigned a slightly higher energy value in the cost # field. For example, if an agent wishes to go to a point, it might # encounter different kind of terrain like grass and dirt. Grass is # assigned medium difficulty of passage (color coded as green on the # map here). Dirt is assigned hard difficulty of passage (color coded # as brown here). Hence, this algorithm will take into account how # difficult it is to go through certain areas of a map when deciding # the shortest path. # draw paths that have medium difficulty (in terms of going through them) all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [10, 45] all_y = [22, 20] all_len = [8, 5] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, m_x, m_y, obs_dict, 'medium') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [20, 30, 42] + [47] * 5 all_y = [35, 30, 38] + [37 + i for i in range(2)] all_len = [5, 7, 3] + [1] * 3 for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, m_x, m_y, obs_dict, 'medium') # draw paths that have hard difficulty (in terms of going through them) all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [15, 20, 35] all_y = [45, 20, 35] all_len = [3, 5, 7] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, h_x, h_y, obs_dict, 'hard') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [30] + [47] * 5 all_y = [10] + [37 + i for i in range(2)] all_len = [5] + [1] * 3 for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, h_x, h_y, obs_dict, 'hard') if show_animation: plt.plot(o_x, o_y, "sr") plt.plot(m_x, m_y, "sg") plt.plot(h_x, h_y, "sy") plt.plot(s_x, s_y, "og") plt.plot(g_x, g_y, "o") plt.grid(True) flow_obj = FlowField(obs_dict, g_x, g_y, s_x, s_y, 50, 50) flow_obj.find_path()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L142-L223
2
[ 0, 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, 79, 80, 81 ]
92.682927
[ 73, 74, 75, 76, 77, 78 ]
7.317073
false
93.377483
82
12
92.682927
0
def main(): # set obstacle positions obs_dict = {} for i in range(51): for j in range(51): obs_dict[(i, j)] = 'free' o_x, o_y, m_x, m_y, h_x, h_y = [], [], [], [], [], [] s_x = 5.0 s_y = 5.0 g_x = 35.0 g_y = 45.0 # draw outer border of maze draw_vertical_line(0, 0, 50, o_x, o_y, obs_dict, 'obs') draw_vertical_line(48, 0, 50, o_x, o_y, obs_dict, 'obs') draw_horizontal_line(0, 0, 50, o_x, o_y, obs_dict, 'obs') draw_horizontal_line(0, 48, 50, o_x, o_y, obs_dict, 'obs') # draw inner walls all_x = [10, 10, 10, 15, 20, 20, 30, 30, 35, 30, 40, 45] all_y = [10, 30, 45, 20, 5, 40, 10, 40, 5, 40, 10, 25] all_len = [10, 10, 5, 10, 10, 5, 20, 10, 25, 10, 35, 15] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, o_x, o_y, obs_dict, 'obs') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [35, 40, 15, 10, 45, 20, 10, 15, 25, 45, 10, 30, 10, 40] all_y = [5, 10, 15, 20, 20, 25, 30, 35, 35, 35, 40, 40, 45, 45] all_len = [10, 5, 10, 10, 5, 5, 10, 5, 10, 5, 10, 5, 5, 5] for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, o_x, o_y, obs_dict, 'obs') # Some points are assigned a slightly higher energy value in the cost # field. For example, if an agent wishes to go to a point, it might # encounter different kind of terrain like grass and dirt. Grass is # assigned medium difficulty of passage (color coded as green on the # map here). Dirt is assigned hard difficulty of passage (color coded # as brown here). Hence, this algorithm will take into account how # difficult it is to go through certain areas of a map when deciding # the shortest path. # draw paths that have medium difficulty (in terms of going through them) all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [10, 45] all_y = [22, 20] all_len = [8, 5] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, m_x, m_y, obs_dict, 'medium') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [20, 30, 42] + [47] * 5 all_y = [35, 30, 38] + [37 + i for i in range(2)] all_len = [5, 7, 3] + [1] * 3 for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, m_x, m_y, obs_dict, 'medium') # draw paths that have hard difficulty (in terms of going through them) all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [15, 20, 35] all_y = [45, 20, 35] all_len = [3, 5, 7] for x, y, l in zip(all_x, all_y, all_len): draw_vertical_line(x, y, l, h_x, h_y, obs_dict, 'hard') all_x[:], all_y[:], all_len[:] = [], [], [] all_x = [30] + [47] * 5 all_y = [10] + [37 + i for i in range(2)] all_len = [5] + [1] * 3 for x, y, l in zip(all_x, all_y, all_len): draw_horizontal_line(x, y, l, h_x, h_y, obs_dict, 'hard') if show_animation: plt.plot(o_x, o_y, "sr") plt.plot(m_x, m_y, "sg") plt.plot(h_x, h_y, "sy") plt.plot(s_x, s_y, "og") plt.plot(g_x, g_y, "o") plt.grid(True) flow_obj = FlowField(obs_dict, g_x, g_y, s_x, s_y, 50, 50) flow_obj.find_path()
751
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.__init__
(self, obs_grid, goal_x, goal_y, start_x, start_y, limit_x, limit_y)
30
38
def __init__(self, obs_grid, goal_x, goal_y, start_x, start_y, limit_x, limit_y): self.start_pt = [start_x, start_y] self.goal_pt = [goal_x, goal_y] self.obs_grid = obs_grid self.limit_x, self.limit_y = limit_x, limit_y self.cost_field = {} self.integration_field = {} self.vector_field = {}
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L30-L38
2
[ 0, 2, 3, 4, 5, 6, 7, 8 ]
88.888889
[]
0
false
93.377483
9
1
100
0
def __init__(self, obs_grid, goal_x, goal_y, start_x, start_y, limit_x, limit_y): self.start_pt = [start_x, start_y] self.goal_pt = [goal_x, goal_y] self.obs_grid = obs_grid self.limit_x, self.limit_y = limit_x, limit_y self.cost_field = {} self.integration_field = {} self.vector_field = {}
752
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.find_path
(self)
40
44
def find_path(self): self.create_cost_field() self.create_integration_field() self.assign_vectors() self.follow_vectors()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L40-L44
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
93.377483
5
1
100
0
def find_path(self): self.create_cost_field() self.create_integration_field() self.assign_vectors() self.follow_vectors()
753
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.create_cost_field
(self)
Assign cost to each grid which defines the energy it would take to get there.
Assign cost to each grid which defines the energy it would take to get there.
46
61
def create_cost_field(self): """Assign cost to each grid which defines the energy it would take to get there.""" for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'free': self.cost_field[(i, j)] = 1 elif self.obs_grid[(i, j)] == 'medium': self.cost_field[(i, j)] = 7 elif self.obs_grid[(i, j)] == 'hard': self.cost_field[(i, j)] = 20 elif self.obs_grid[(i, j)] == 'obs': continue if [i, j] == self.goal_pt: self.cost_field[(i, j)] = 0
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L46-L61
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
93.377483
16
8
100
2
def create_cost_field(self): for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'free': self.cost_field[(i, j)] = 1 elif self.obs_grid[(i, j)] == 'medium': self.cost_field[(i, j)] = 7 elif self.obs_grid[(i, j)] == 'hard': self.cost_field[(i, j)] = 20 elif self.obs_grid[(i, j)] == 'obs': continue if [i, j] == self.goal_pt: self.cost_field[(i, j)] = 0
754
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.create_integration_field
(self)
Start from the goal node and calculate the value of the integration field at each node. Start by assigning a value of infinity to every node except the goal node which is assigned a value of 0. Put the goal node in the open list and then get its neighbors (must not be obstacles). For each neighbor, the new cost is equal to the cost of the current node in the integration field (in the beginning, this will simply be the goal node) + the cost of the neighbor in the cost field + the extra cost (optional). The new cost is only assigned if it is less than the previously assigned cost of the node in the integration field and, when that happens, the neighbor is put on the open list. This process continues until the open list is empty.
Start from the goal node and calculate the value of the integration field at each node. Start by assigning a value of infinity to every node except the goal node which is assigned a value of 0. Put the goal node in the open list and then get its neighbors (must not be obstacles). For each neighbor, the new cost is equal to the cost of the current node in the integration field (in the beginning, this will simply be the goal node) + the cost of the neighbor in the cost field + the extra cost (optional). The new cost is only assigned if it is less than the previously assigned cost of the node in the integration field and, when that happens, the neighbor is put on the open list. This process continues until the open list is empty.
63
105
def create_integration_field(self): """Start from the goal node and calculate the value of the integration field at each node. Start by assigning a value of infinity to every node except the goal node which is assigned a value of 0. Put the goal node in the open list and then get its neighbors (must not be obstacles). For each neighbor, the new cost is equal to the cost of the current node in the integration field (in the beginning, this will simply be the goal node) + the cost of the neighbor in the cost field + the extra cost (optional). The new cost is only assigned if it is less than the previously assigned cost of the node in the integration field and, when that happens, the neighbor is put on the open list. This process continues until the open list is empty.""" for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'obs': continue self.integration_field[(i, j)] = np.inf if [i, j] == self.goal_pt: self.integration_field[(i, j)] = 0 open_list = [(self.goal_pt, 0)] while open_list: curr_pos, curr_cost = open_list[0] curr_x, curr_y = curr_pos for i in range(-1, 2): for j in range(-1, 2): x, y = curr_x + i, curr_y + j if self.obs_grid[(x, y)] == 'obs': continue if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]: e_cost = 10 else: e_cost = 14 neighbor_energy = self.cost_field[(x, y)] neighbor_old_cost = self.integration_field[(x, y)] neighbor_new_cost = curr_cost + neighbor_energy + e_cost if neighbor_new_cost < neighbor_old_cost: self.integration_field[(x, y)] = neighbor_new_cost open_list.append(([x, y], neighbor_new_cost)) del open_list[0]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L63-L105
2
[ 0, 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, 35, 36, 37, 38, 39, 40, 41, 42 ]
97.674419
[]
0
false
93.377483
43
11
100
14
def create_integration_field(self): for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'obs': continue self.integration_field[(i, j)] = np.inf if [i, j] == self.goal_pt: self.integration_field[(i, j)] = 0 open_list = [(self.goal_pt, 0)] while open_list: curr_pos, curr_cost = open_list[0] curr_x, curr_y = curr_pos for i in range(-1, 2): for j in range(-1, 2): x, y = curr_x + i, curr_y + j if self.obs_grid[(x, y)] == 'obs': continue if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]: e_cost = 10 else: e_cost = 14 neighbor_energy = self.cost_field[(x, y)] neighbor_old_cost = self.integration_field[(x, y)] neighbor_new_cost = curr_cost + neighbor_energy + e_cost if neighbor_new_cost < neighbor_old_cost: self.integration_field[(x, y)] = neighbor_new_cost open_list.append(([x, y], neighbor_new_cost)) del open_list[0]
755
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.assign_vectors
(self)
For each node, assign a vector from itself to the node with the lowest cost in the integration field. An agent will simply follow this vector field to the goal
For each node, assign a vector from itself to the node with the lowest cost in the integration field. An agent will simply follow this vector field to the goal
107
127
def assign_vectors(self): """For each node, assign a vector from itself to the node with the lowest cost in the integration field. An agent will simply follow this vector field to the goal""" for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'obs': continue if [i, j] == self.goal_pt: self.vector_field[(i, j)] = (None, None) continue offset_list = [(i + a, j + b) for a in range(-1, 2) for b in range(-1, 2)] neighbor_list = [{'loc': pt, 'cost': self.integration_field[pt]} for pt in offset_list if self.obs_grid[pt] != 'obs'] neighbor_list = sorted(neighbor_list, key=lambda x: x['cost']) best_neighbor = neighbor_list[0]['loc'] self.vector_field[(i, j)] = best_neighbor
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L107-L127
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 18, 19, 20 ]
76.190476
[]
0
false
93.377483
21
7
100
3
def assign_vectors(self): for i in range(self.limit_x): for j in range(self.limit_y): if self.obs_grid[(i, j)] == 'obs': continue if [i, j] == self.goal_pt: self.vector_field[(i, j)] = (None, None) continue offset_list = [(i + a, j + b) for a in range(-1, 2) for b in range(-1, 2)] neighbor_list = [{'loc': pt, 'cost': self.integration_field[pt]} for pt in offset_list if self.obs_grid[pt] != 'obs'] neighbor_list = sorted(neighbor_list, key=lambda x: x['cost']) best_neighbor = neighbor_list[0]['loc'] self.vector_field[(i, j)] = best_neighbor
756
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/FlowField/flowfield.py
FlowField.follow_vectors
(self)
129
139
def follow_vectors(self): curr_x, curr_y = self.start_pt while curr_x is not None and curr_y is not None: curr_x, curr_y = self.vector_field[(curr_x, curr_y)] if show_animation: plt.plot(curr_x, curr_y, "b*") plt.pause(0.001) if show_animation: plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/FlowField/flowfield.py#L129-L139
2
[ 0, 1, 2, 3, 4, 5, 8, 9 ]
72.727273
[ 6, 7, 10 ]
27.272727
false
93.377483
11
5
72.727273
0
def follow_vectors(self): curr_x, curr_y = self.start_pt while curr_x is not None and curr_y is not None: curr_x, curr_y = self.vector_field[(curr_x, curr_y)] if show_animation: plt.plot(curr_x, curr_y, "b*") plt.pause(0.001) if show_animation: plt.show()
757
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
main
(maxIter=80)
611
631
def main(maxIter=80): print("Starting Batch Informed Trees Star planning") obstacleList = [ (5, 5, 0.5), (9, 6, 1), (7, 5, 1), (1, 5, 1), (3, 6, 1), (7, 9, 1) ] bitStar = BITStar(start=[-1, 0], goal=[3, 8], obstacleList=obstacleList, randArea=[-2, 15], maxIter=maxIter) path = bitStar.plan(animation=show_animation) print("Done") if show_animation: plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r') plt.grid(True) plt.pause(0.05) plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L611-L631
2
[ 0, 1, 2, 10, 11, 13, 14, 15, 16 ]
42.857143
[ 17, 18, 19, 20 ]
19.047619
false
82.681564
21
4
80.952381
0
def main(maxIter=80): print("Starting Batch Informed Trees Star planning") obstacleList = [ (5, 5, 0.5), (9, 6, 1), (7, 5, 1), (1, 5, 1), (3, 6, 1), (7, 9, 1) ] bitStar = BITStar(start=[-1, 0], goal=[3, 8], obstacleList=obstacleList, randArea=[-2, 15], maxIter=maxIter) path = bitStar.plan(animation=show_animation) print("Done") if show_animation: plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r') plt.grid(True) plt.pause(0.05) plt.show()
772
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.__init__
(self, start=None, lowerLimit=None, upperLimit=None, resolution=1.0)
30
54
def __init__(self, start=None, lowerLimit=None, upperLimit=None, resolution=1.0): if upperLimit is None: upperLimit = [10, 10] if lowerLimit is None: lowerLimit = [0, 0] if start is None: start = [0, 0] self.vertices = dict() self.edges = [] self.start = start self.lowerLimit = lowerLimit self.upperLimit = upperLimit self.dimension = len(lowerLimit) self.num_cells = [0] * self.dimension self.resolution = resolution # compute the number of grid cells based on the limits and # resolution given for idx in range(self.dimension): self.num_cells[idx] = np.ceil( (upperLimit[idx] - lowerLimit[idx]) / resolution) vertex_id = self.real_world_to_node_id(start) self.vertices[vertex_id] = []
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L30-L54
2
[ 0, 2, 3, 5, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24 ]
80
[ 4, 6, 8 ]
12
false
82.681564
25
5
88
0
def __init__(self, start=None, lowerLimit=None, upperLimit=None, resolution=1.0): if upperLimit is None: upperLimit = [10, 10] if lowerLimit is None: lowerLimit = [0, 0] if start is None: start = [0, 0] self.vertices = dict() self.edges = [] self.start = start self.lowerLimit = lowerLimit self.upperLimit = upperLimit self.dimension = len(lowerLimit) self.num_cells = [0] * self.dimension self.resolution = resolution # compute the number of grid cells based on the limits and # resolution given for idx in range(self.dimension): self.num_cells[idx] = np.ceil( (upperLimit[idx] - lowerLimit[idx]) / resolution) vertex_id = self.real_world_to_node_id(start) self.vertices[vertex_id] = []
773
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.get_root_id
()
return 0
57
59
def get_root_id(): # return the id of the root of the tree return 0
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L57-L59
2
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
82.681564
3
1
66.666667
0
def get_root_id(): # return the id of the root of the tree return 0
774
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.add_vertex
(self, vertex)
return vertex_id
61
65
def add_vertex(self, vertex): # add a vertex to the tree vertex_id = self.real_world_to_node_id(vertex) self.vertices[vertex_id] = [] return vertex_id
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L61-L65
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
82.681564
5
1
100
0
def add_vertex(self, vertex): # add a vertex to the tree vertex_id = self.real_world_to_node_id(vertex) self.vertices[vertex_id] = [] return vertex_id
775
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.add_edge
(self, v, x)
67
73
def add_edge(self, v, x): # create an edge between v and x vertices if (v, x) not in self.edges: self.edges.append((v, x)) # since the tree is undirected self.vertices[v].append(x) self.vertices[x].append(v)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L67-L73
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
82.681564
7
2
100
0
def add_edge(self, v, x): # create an edge between v and x vertices if (v, x) not in self.edges: self.edges.append((v, x)) # since the tree is undirected self.vertices[v].append(x) self.vertices[x].append(v)
776
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.real_coords_to_grid_coord
(self, real_coord)
return coord
75
84
def real_coords_to_grid_coord(self, real_coord): # convert real world coordinates to grid space # depends on the resolution of the grid # the output is the same as real world coords if the resolution # is set to 1 coord = [0] * self.dimension for i in range(len(coord)): start = self.lowerLimit[i] # start of the grid space coord[i] = int(np.around((real_coord[i] - start) / self.resolution)) return coord
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L75-L84
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
82.681564
10
2
100
0
def real_coords_to_grid_coord(self, real_coord): # convert real world coordinates to grid space # depends on the resolution of the grid # the output is the same as real world coords if the resolution # is set to 1 coord = [0] * self.dimension for i in range(len(coord)): start = self.lowerLimit[i] # start of the grid space coord[i] = int(np.around((real_coord[i] - start) / self.resolution)) return coord
777
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.grid_coordinate_to_node_id
(self, coord)
return nodeId
86
95
def grid_coordinate_to_node_id(self, coord): # This function maps a grid coordinate to a unique # node id nodeId = 0 for i in range(len(coord) - 1, -1, -1): product = 1 for j in range(0, i): product = product * self.num_cells[j] nodeId = nodeId + coord[i] * product return nodeId
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L86-L95
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
82.681564
10
3
100
0
def grid_coordinate_to_node_id(self, coord): # This function maps a grid coordinate to a unique # node id nodeId = 0 for i in range(len(coord) - 1, -1, -1): product = 1 for j in range(0, i): product = product * self.num_cells[j] nodeId = nodeId + coord[i] * product return nodeId
778
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.real_world_to_node_id
(self, real_coord)
return self.grid_coordinate_to_node_id( self.real_coords_to_grid_coord(real_coord))
97
101
def real_world_to_node_id(self, real_coord): # first convert the given coordinates to grid space and then # convert the grid space coordinates to a unique node id return self.grid_coordinate_to_node_id( self.real_coords_to_grid_coord(real_coord))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L97-L101
2
[ 0, 1, 2, 3 ]
80
[]
0
false
82.681564
5
1
100
0
def real_world_to_node_id(self, real_coord): # first convert the given coordinates to grid space and then # convert the grid space coordinates to a unique node id return self.grid_coordinate_to_node_id( self.real_coords_to_grid_coord(real_coord))
779
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.grid_coord_to_real_world_coord
(self, coord)
return config
103
113
def grid_coord_to_real_world_coord(self, coord): # This function maps a grid coordinate in discrete space # to a configuration in the full configuration space config = [0] * self.dimension for i in range(0, len(coord)): # start of the real world / configuration space start = self.lowerLimit[i] # step from the coordinate in the grid grid_step = self.resolution * coord[i] config[i] = start + grid_step return config
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L103-L113
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
82.681564
11
2
100
0
def grid_coord_to_real_world_coord(self, coord): # This function maps a grid coordinate in discrete space # to a configuration in the full configuration space config = [0] * self.dimension for i in range(0, len(coord)): # start of the real world / configuration space start = self.lowerLimit[i] # step from the coordinate in the grid grid_step = self.resolution * coord[i] config[i] = start + grid_step return config
780
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.node_id_to_grid_coord
(self, node_id)
return coord
115
126
def node_id_to_grid_coord(self, node_id): # This function maps a node id to the associated # grid coordinate coord = [0] * len(self.lowerLimit) for i in range(len(coord) - 1, -1, -1): # Get the product of the grid space maximums prod = 1 for j in range(0, i): prod = prod * self.num_cells[j] coord[i] = np.floor(node_id / prod) node_id = node_id - (coord[i] * prod) return coord
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L115-L126
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
82.681564
12
3
100
0
def node_id_to_grid_coord(self, node_id): # This function maps a node id to the associated # grid coordinate coord = [0] * len(self.lowerLimit) for i in range(len(coord) - 1, -1, -1): # Get the product of the grid space maximums prod = 1 for j in range(0, i): prod = prod * self.num_cells[j] coord[i] = np.floor(node_id / prod) node_id = node_id - (coord[i] * prod) return coord
781
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
RTree.node_id_to_real_world_coord
(self, nid)
return self.grid_coord_to_real_world_coord( self.node_id_to_grid_coord(nid))
128
132
def node_id_to_real_world_coord(self, nid): # This function maps a node in discrete space to a configuration # in the full configuration space return self.grid_coord_to_real_world_coord( self.node_id_to_grid_coord(nid))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L128-L132
2
[ 0, 1, 2, 3 ]
80
[]
0
false
82.681564
5
1
100
0
def node_id_to_real_world_coord(self, nid): # This function maps a node in discrete space to a configuration # in the full configuration space return self.grid_coord_to_real_world_coord( self.node_id_to_grid_coord(nid))
782
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.__init__
(self, start, goal, obstacleList, randArea, eta=2.0, maxIter=80)
137
165
def __init__(self, start, goal, obstacleList, randArea, eta=2.0, maxIter=80): self.start = start self.goal = goal self.min_rand = randArea[0] self.max_rand = randArea[1] self.max_iIter = maxIter self.obstacleList = obstacleList self.startId = None self.goalId = None self.vertex_queue = [] self.edge_queue = [] self.samples = dict() self.g_scores = dict() self.f_scores = dict() self.nodes = dict() self.r = float('inf') self.eta = eta # tunable parameter self.unit_ball_measure = 1 self.old_vertices = [] # initialize tree lowerLimit = [randArea[0], randArea[0]] upperLimit = [randArea[1], randArea[1]] self.tree = RTree(start=start, lowerLimit=lowerLimit, upperLimit=upperLimit, resolution=0.01)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L137-L165
2
[ 0, 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 ]
89.655172
[]
0
false
82.681564
29
1
100
0
def __init__(self, start, goal, obstacleList, randArea, eta=2.0, maxIter=80): self.start = start self.goal = goal self.min_rand = randArea[0] self.max_rand = randArea[1] self.max_iIter = maxIter self.obstacleList = obstacleList self.startId = None self.goalId = None self.vertex_queue = [] self.edge_queue = [] self.samples = dict() self.g_scores = dict() self.f_scores = dict() self.nodes = dict() self.r = float('inf') self.eta = eta # tunable parameter self.unit_ball_measure = 1 self.old_vertices = [] # initialize tree lowerLimit = [randArea[0], randArea[0]] upperLimit = [randArea[1], randArea[1]] self.tree = RTree(start=start, lowerLimit=lowerLimit, upperLimit=upperLimit, resolution=0.01)
783
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.setup_planning
(self)
return eTheta, cMin, xCenter, C, cBest
167
204
def setup_planning(self): self.startId = self.tree.real_world_to_node_id(self.start) self.goalId = self.tree.real_world_to_node_id(self.goal) # add goal to the samples self.samples[self.goalId] = self.goal self.g_scores[self.goalId] = float('inf') self.f_scores[self.goalId] = 0 # add the start id to the tree self.tree.add_vertex(self.start) self.g_scores[self.startId] = 0 self.f_scores[self.startId] = self.compute_heuristic_cost( self.startId, self.goalId) # max length we expect to find in our 'informed' sample space, starts as infinite cBest = self.g_scores[self.goalId] # Computing the sampling space cMin = math.hypot(self.start[0] - self.goal[0], self.start[1] - self.goal[1]) / 1.5 xCenter = np.array([[(self.start[0] + self.goal[0]) / 2.0], [(self.start[1] + self.goal[1]) / 2.0], [0]]) a1 = np.array([[(self.goal[0] - self.start[0]) / cMin], [(self.goal[1] - self.start[1]) / cMin], [0]]) eTheta = math.atan2(a1[1], a1[0]) # first column of identity matrix transposed id1_t = np.array([1.0, 0.0, 0.0]).reshape(1, 3) M = np.dot(a1, id1_t) U, S, Vh = np.linalg.svd(M, True, True) C = np.dot(np.dot(U, np.diag( [1.0, 1.0, np.linalg.det(U) * np.linalg.det(np.transpose(Vh))])), Vh) self.samples.update(self.informed_sample( 200, cBest, cMin, xCenter, C)) return eTheta, cMin, xCenter, C, cBest
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L167-L204
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18, 19, 21, 23, 25, 26, 27, 28, 29, 30, 33, 34, 36, 37 ]
78.947368
[]
0
false
82.681564
38
1
100
0
def setup_planning(self): self.startId = self.tree.real_world_to_node_id(self.start) self.goalId = self.tree.real_world_to_node_id(self.goal) # add goal to the samples self.samples[self.goalId] = self.goal self.g_scores[self.goalId] = float('inf') self.f_scores[self.goalId] = 0 # add the start id to the tree self.tree.add_vertex(self.start) self.g_scores[self.startId] = 0 self.f_scores[self.startId] = self.compute_heuristic_cost( self.startId, self.goalId) # max length we expect to find in our 'informed' sample space, starts as infinite cBest = self.g_scores[self.goalId] # Computing the sampling space cMin = math.hypot(self.start[0] - self.goal[0], self.start[1] - self.goal[1]) / 1.5 xCenter = np.array([[(self.start[0] + self.goal[0]) / 2.0], [(self.start[1] + self.goal[1]) / 2.0], [0]]) a1 = np.array([[(self.goal[0] - self.start[0]) / cMin], [(self.goal[1] - self.start[1]) / cMin], [0]]) eTheta = math.atan2(a1[1], a1[0]) # first column of identity matrix transposed id1_t = np.array([1.0, 0.0, 0.0]).reshape(1, 3) M = np.dot(a1, id1_t) U, S, Vh = np.linalg.svd(M, True, True) C = np.dot(np.dot(U, np.diag( [1.0, 1.0, np.linalg.det(U) * np.linalg.det(np.transpose(Vh))])), Vh) self.samples.update(self.informed_sample( 200, cBest, cMin, xCenter, C)) return eTheta, cMin, xCenter, C, cBest
784
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.setup_sample
(self, iterations, foundGoal, cMin, xCenter, C, cBest)
return cBest
206
231
def setup_sample(self, iterations, foundGoal, cMin, xCenter, C, cBest): if len(self.vertex_queue) == 0 and len(self.edge_queue) == 0: print("Batch: ", iterations) # Using informed rrt star way of computing the samples self.r = 2.0 if iterations != 0: if foundGoal: # a better way to do this would be to make number of samples # a function of cMin m = 200 self.samples = dict() self.samples[self.goalId] = self.goal else: m = 100 cBest = self.g_scores[self.goalId] self.samples.update(self.informed_sample( m, cBest, cMin, xCenter, C)) # make the old vertices the new vertices self.old_vertices += self.tree.vertices.keys() # add the vertices to the vertex queue for nid in self.tree.vertices.keys(): if nid not in self.vertex_queue: self.vertex_queue.append(nid) return cBest
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L206-L231
2
[ 0, 1, 2, 3, 4, 5, 6, 19, 20, 21, 22, 23, 24, 25 ]
53.846154
[ 7, 10, 11, 12, 14, 15, 16 ]
26.923077
false
82.681564
26
7
73.076923
0
def setup_sample(self, iterations, foundGoal, cMin, xCenter, C, cBest): if len(self.vertex_queue) == 0 and len(self.edge_queue) == 0: print("Batch: ", iterations) # Using informed rrt star way of computing the samples self.r = 2.0 if iterations != 0: if foundGoal: # a better way to do this would be to make number of samples # a function of cMin m = 200 self.samples = dict() self.samples[self.goalId] = self.goal else: m = 100 cBest = self.g_scores[self.goalId] self.samples.update(self.informed_sample( m, cBest, cMin, xCenter, C)) # make the old vertices the new vertices self.old_vertices += self.tree.vertices.keys() # add the vertices to the vertex queue for nid in self.tree.vertices.keys(): if nid not in self.vertex_queue: self.vertex_queue.append(nid) return cBest
785
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.plan
(self, animation=True)
return self.find_final_path()
233
328
def plan(self, animation=True): eTheta, cMin, xCenter, C, cBest = self.setup_planning() iterations = 0 foundGoal = False # run until done while iterations < self.max_iIter: cBest = self.setup_sample(iterations, foundGoal, cMin, xCenter, C, cBest) # expand the best vertices until an edge is better than the vertex # this is done because the vertex cost represents the lower bound # on the edge cost while self.best_vertex_queue_value() <= \ self.best_edge_queue_value(): self.expand_vertex(self.best_in_vertex_queue()) # add the best edge to the tree bestEdge = self.best_in_edge_queue() self.edge_queue.remove(bestEdge) # Check if this can improve the current solution estimatedCostOfVertex = self.g_scores[bestEdge[ 0]] + self.compute_distance_cost( bestEdge[0], bestEdge[1]) + self.compute_heuristic_cost( bestEdge[1], self.goalId) estimatedCostOfEdge = self.compute_distance_cost( self.startId, bestEdge[0]) + self.compute_heuristic_cost( bestEdge[0], bestEdge[1]) + self.compute_heuristic_cost( bestEdge[1], self.goalId) actualCostOfEdge = self.g_scores[ bestEdge[0]] + self.compute_distance_cost( bestEdge[0], bestEdge[1]) f1 = estimatedCostOfVertex < self.g_scores[self.goalId] f2 = estimatedCostOfEdge < self.g_scores[self.goalId] f3 = actualCostOfEdge < self.g_scores[self.goalId] if f1 and f2 and f3: # connect this edge firstCoord = self.tree.node_id_to_real_world_coord( bestEdge[0]) secondCoord = self.tree.node_id_to_real_world_coord( bestEdge[1]) path = self.connect(firstCoord, secondCoord) lastEdge = self.tree.real_world_to_node_id(secondCoord) if path is None or len(path) == 0: continue nextCoord = path[len(path) - 1, :] nextCoordPathId = self.tree.real_world_to_node_id( nextCoord) bestEdge = (bestEdge[0], nextCoordPathId) if bestEdge[1] in self.tree.vertices.keys(): continue else: try: del self.samples[bestEdge[1]] except KeyError: # invalid sample key pass eid = self.tree.add_vertex(nextCoord) self.vertex_queue.append(eid) if eid == self.goalId or bestEdge[0] == self.goalId or \ bestEdge[1] == self.goalId: print("Goal found") foundGoal = True self.tree.add_edge(bestEdge[0], bestEdge[1]) g_score = self.compute_distance_cost( bestEdge[0], bestEdge[1]) self.g_scores[bestEdge[1]] = g_score + self.g_scores[ bestEdge[0]] self.f_scores[ bestEdge[1]] = g_score + self.compute_heuristic_cost( bestEdge[1], self.goalId) self.update_graph() # visualize new edge if animation: self.draw_graph(xCenter=xCenter, cBest=cBest, cMin=cMin, eTheta=eTheta, samples=self.samples.values(), start=firstCoord, end=secondCoord) self.remove_queue(lastEdge, bestEdge) else: print("Nothing good") self.edge_queue = [] self.vertex_queue = [] iterations += 1 print("Finding the path") return self.find_final_path()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L233-L328
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26, 30, 33, 34, 35, 36, 37, 38, 39, 40, 42, 44, 45, 46, 48, 49, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, 66, 67, 68, 69, 71, 73, 76, 77, 78, 79, 84, 85, 86, 91, 92, 93, 94, 95 ]
66.666667
[ 47, 64, 65, 80, 88, 89, 90 ]
7.291667
false
82.681564
96
14
92.708333
0
def plan(self, animation=True): eTheta, cMin, xCenter, C, cBest = self.setup_planning() iterations = 0 foundGoal = False # run until done while iterations < self.max_iIter: cBest = self.setup_sample(iterations, foundGoal, cMin, xCenter, C, cBest) # expand the best vertices until an edge is better than the vertex # this is done because the vertex cost represents the lower bound # on the edge cost while self.best_vertex_queue_value() <= \ self.best_edge_queue_value(): self.expand_vertex(self.best_in_vertex_queue()) # add the best edge to the tree bestEdge = self.best_in_edge_queue() self.edge_queue.remove(bestEdge) # Check if this can improve the current solution estimatedCostOfVertex = self.g_scores[bestEdge[ 0]] + self.compute_distance_cost( bestEdge[0], bestEdge[1]) + self.compute_heuristic_cost( bestEdge[1], self.goalId) estimatedCostOfEdge = self.compute_distance_cost( self.startId, bestEdge[0]) + self.compute_heuristic_cost( bestEdge[0], bestEdge[1]) + self.compute_heuristic_cost( bestEdge[1], self.goalId) actualCostOfEdge = self.g_scores[ bestEdge[0]] + self.compute_distance_cost( bestEdge[0], bestEdge[1]) f1 = estimatedCostOfVertex < self.g_scores[self.goalId] f2 = estimatedCostOfEdge < self.g_scores[self.goalId] f3 = actualCostOfEdge < self.g_scores[self.goalId] if f1 and f2 and f3: # connect this edge firstCoord = self.tree.node_id_to_real_world_coord( bestEdge[0]) secondCoord = self.tree.node_id_to_real_world_coord( bestEdge[1]) path = self.connect(firstCoord, secondCoord) lastEdge = self.tree.real_world_to_node_id(secondCoord) if path is None or len(path) == 0: continue nextCoord = path[len(path) - 1, :] nextCoordPathId = self.tree.real_world_to_node_id( nextCoord) bestEdge = (bestEdge[0], nextCoordPathId) if bestEdge[1] in self.tree.vertices.keys(): continue else: try: del self.samples[bestEdge[1]] except KeyError: # invalid sample key pass eid = self.tree.add_vertex(nextCoord) self.vertex_queue.append(eid) if eid == self.goalId or bestEdge[0] == self.goalId or \ bestEdge[1] == self.goalId: print("Goal found") foundGoal = True self.tree.add_edge(bestEdge[0], bestEdge[1]) g_score = self.compute_distance_cost( bestEdge[0], bestEdge[1]) self.g_scores[bestEdge[1]] = g_score + self.g_scores[ bestEdge[0]] self.f_scores[ bestEdge[1]] = g_score + self.compute_heuristic_cost( bestEdge[1], self.goalId) self.update_graph() # visualize new edge if animation: self.draw_graph(xCenter=xCenter, cBest=cBest, cMin=cMin, eTheta=eTheta, samples=self.samples.values(), start=firstCoord, end=secondCoord) self.remove_queue(lastEdge, bestEdge) else: print("Nothing good") self.edge_queue = [] self.vertex_queue = [] iterations += 1 print("Finding the path") return self.find_final_path()
786
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.find_final_path
(self)
return plan
330
344
def find_final_path(self): plan = [self.goal] currId = self.goalId while currId != self.startId: plan.append(self.tree.node_id_to_real_world_coord(currId)) try: currId = self.nodes[currId] except KeyError: print("cannot find Path") return [] plan.append(self.start) plan = plan[::-1] # reverse the plan return plan
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L330-L344
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
73.333333
[ 11, 12, 14 ]
20
false
82.681564
15
3
80
0
def find_final_path(self): plan = [self.goal] currId = self.goalId while currId != self.startId: plan.append(self.tree.node_id_to_real_world_coord(currId)) try: currId = self.nodes[currId] except KeyError: print("cannot find Path") return [] plan.append(self.start) plan = plan[::-1] # reverse the plan return plan
787
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.remove_queue
(self, lastEdge, bestEdge)
346
354
def remove_queue(self, lastEdge, bestEdge): for edge in self.edge_queue: if edge[1] == bestEdge[1]: dist_cost = self.compute_distance_cost(edge[1], bestEdge[1]) if self.g_scores[edge[1]] + dist_cost >= \ self.g_scores[self.goalId]: if (lastEdge, bestEdge[1]) in self.edge_queue: self.edge_queue.remove( (lastEdge, bestEdge[1]))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L346-L354
2
[ 0, 1, 2, 3, 4 ]
55.555556
[ 6, 7 ]
22.222222
false
82.681564
9
5
77.777778
0
def remove_queue(self, lastEdge, bestEdge): for edge in self.edge_queue: if edge[1] == bestEdge[1]: dist_cost = self.compute_distance_cost(edge[1], bestEdge[1]) if self.g_scores[edge[1]] + dist_cost >= \ self.g_scores[self.goalId]: if (lastEdge, bestEdge[1]) in self.edge_queue: self.edge_queue.remove( (lastEdge, bestEdge[1]))
788
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.connect
(self, start, end)
return np.vstack((x, y)).transpose()
356
371
def connect(self, start, end): # A function which attempts to extend from a start coordinates # to goal coordinates steps = int(self.compute_distance_cost( self.tree.real_world_to_node_id(start), self.tree.real_world_to_node_id(end)) * 10) x = np.linspace(start[0], end[0], num=steps) y = np.linspace(start[1], end[1], num=steps) for i in range(len(x)): if self._collision_check(x[i], y[i]): if i == 0: return None # if collision, send path until collision return np.vstack((x[0:i], y[0:i])).transpose() return np.vstack((x, y)).transpose()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L356-L371
2
[ 0, 1, 2, 3, 6, 7, 8, 9, 10, 12, 13, 14, 15 ]
81.25
[ 11 ]
6.25
false
82.681564
16
4
93.75
0
def connect(self, start, end): # A function which attempts to extend from a start coordinates # to goal coordinates steps = int(self.compute_distance_cost( self.tree.real_world_to_node_id(start), self.tree.real_world_to_node_id(end)) * 10) x = np.linspace(start[0], end[0], num=steps) y = np.linspace(start[1], end[1], num=steps) for i in range(len(x)): if self._collision_check(x[i], y[i]): if i == 0: return None # if collision, send path until collision return np.vstack((x[0:i], y[0:i])).transpose() return np.vstack((x, y)).transpose()
789
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar._collision_check
(self, x, y)
return False
373
380
def _collision_check(self, x, y): for (ox, oy, size) in self.obstacleList: dx = ox - x dy = oy - y d = dx * dx + dy * dy if d <= size ** 2: return True # collision return False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L373-L380
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
82.681564
8
3
100
0
def _collision_check(self, x, y): for (ox, oy, size) in self.obstacleList: dx = ox - x dy = oy - y d = dx * dx + dy * dy if d <= size ** 2: return True # collision return False
790
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py
BITStar.compute_heuristic_cost
(self, start_id, goal_id)
return np.linalg.norm(start - goal, 2)
382
387
def compute_heuristic_cost(self, start_id, goal_id): # Using Manhattan distance as heuristic start = np.array(self.tree.node_id_to_real_world_coord(start_id)) goal = np.array(self.tree.node_id_to_real_world_coord(goal_id)) return np.linalg.norm(start - goal, 2)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py#L382-L387
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
82.681564
6
1
100
0
def compute_heuristic_cost(self, start_id, goal_id): # Using Manhattan distance as heuristic start = np.array(self.tree.node_id_to_real_world_coord(start_id)) goal = np.array(self.tree.node_id_to_real_world_coord(goal_id)) return np.linalg.norm(start - goal, 2)
791