text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```python
"""
Path tracking simulation with LQR speed and steering control
author Atsushi Sakai (@Atsushi_twi)
"""
import math
import sys
import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as la
import pathlib
from utils.angle import angle_mod
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
from PathPlanning.CubicSpline import cubic_spline_planner
# === Parameters =====
# LQR parameter
lqr_Q = np.eye(5)
lqr_R = np.eye(2)
dt = 0.1 # time tick[s]
L = 0.5 # Wheel base of the vehicle [m]
max_steer = np.deg2rad(45.0) # maximum steering angle[rad]
show_animation = True
class State:
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
def update(state, a, delta):
if delta >= max_steer:
delta = max_steer
if 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 / L * math.tan(delta) * dt
state.v = state.v + a * dt
return state
def pi_2_pi(angle):
return angle_mod(angle)
def solve_dare(A, B, Q, R):
"""
solve a discrete time_Algebraic Riccati equation (DARE)
"""
x = Q
x_next = Q
max_iter = 150
eps = 0.01
for i in range(max_iter):
x_next = A.T @ x @ A - A.T @ x @ B @ \
la.inv(R + B.T @ x @ B) @ B.T @ x @ A + Q
if (abs(x_next - x)).max() < eps:
break
x = x_next
return x_next
def dlqr(A, B, Q, R):
"""Solve the discrete time lqr controller.
x[k+1] = A x[k] + B u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
# ref Bertsekas, p.151
"""
# first, try to solve the ricatti equation
X = solve_dare(A, B, Q, R)
# compute the LQR gain
K = la.inv(B.T @ X @ B + R) @ (B.T @ X @ A)
eig_result = la.eig(A - B @ K)
return K, X, eig_result[0]
def lqr_speed_steering_control(state, cx, cy, cyaw, ck, pe, pth_e, sp, Q, R):
ind, e = calc_nearest_index(state, cx, cy, cyaw)
tv = sp[ind]
k = ck[ind]
v = state.v
th_e = pi_2_pi(state.yaw - cyaw[ind])
# A = [1.0, dt, 0.0, 0.0, 0.0
# 0.0, 0.0, v, 0.0, 0.0]
# 0.0, 0.0, 1.0, dt, 0.0]
# 0.0, 0.0, 0.0, 0.0, 0.0]
# 0.0, 0.0, 0.0, 0.0, 1.0]
A = np.zeros((5, 5))
A[0, 0] = 1.0
A[0, 1] = dt
A[1, 2] = v
A[2, 2] = 1.0
A[2, 3] = dt
A[4, 4] = 1.0
# B = [0.0, 0.0
# 0.0, 0.0
# 0.0, 0.0
# v/L, 0.0
# 0.0, dt]
B = np.zeros((5, 2))
B[3, 0] = v / L
B[4, 1] = dt
K, _, _ = dlqr(A, B, Q, R)
# state vector
# x = [e, dot_e, th_e, dot_th_e, delta_v]
# e: lateral distance to the path
# dot_e: derivative of e
# th_e: angle difference to the path
# dot_th_e: derivative of th_e
# delta_v: difference between current speed and target speed
x = np.zeros((5, 1))
x[0, 0] = e
x[1, 0] = (e - pe) / dt
x[2, 0] = th_e
x[3, 0] = (th_e - pth_e) / dt
x[4, 0] = v - tv
# input vector
# u = [delta, accel]
# delta: steering angle
# accel: acceleration
ustar = -K @ x
# calc steering input
ff = math.atan2(L * k, 1) # feedforward steering angle
fb = pi_2_pi(ustar[0, 0]) # feedback steering angle
delta = ff + fb
# calc accel input
accel = ustar[1, 0]
return delta, ind, e, th_e, accel
def calc_nearest_index(state, cx, cy, cyaw):
dx = [state.x - icx for icx in cx]
dy = [state.y - icy for icy in cy]
d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)]
mind = min(d)
ind = d.index(mind)
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
def do_simulation(cx, cy, cyaw, ck, speed_profile, goal):
T = 500.0 # max simulation time
goal_dis = 0.3
stop_speed = 0.05
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]
e, e_th = 0.0, 0.0
while T >= time:
dl, target_ind, e, e_th, ai = lqr_speed_steering_control(
state, cx, cy, cyaw, ck, e, e_th, speed_profile, lqr_Q, lqr_R)
state = update(state, ai, dl)
if abs(state.v) <= stop_speed:
target_ind += 1
time = time + dt
# check goal
dx = state.x - goal[0]
dy = state.y - goal[1]
if math.hypot(dx, dy) <= goal_dis:
print("Goal")
break
x.append(state.x)
y.append(state.y)
yaw.append(state.yaw)
v.append(state.v)
t.append(time)
if target_ind % 1 == 0 and 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(cx, cy, "-r", label="course")
plt.plot(x, y, "ob", label="trajectory")
plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
plt.axis("equal")
plt.grid(True)
plt.title("speed[km/h]:" + str(round(state.v * 3.6, 2))
+ ",target index:" + str(target_ind))
plt.pause(0.0001)
return t, x, y, yaw, v
def calc_speed_profile(cyaw, target_speed):
speed_profile = [target_speed] * len(cyaw)
direction = 1.0
# Set stop point
for i in range(len(cyaw) - 1):
dyaw = abs(cyaw[i + 1] - cyaw[i])
switch = math.pi / 4.0 <= dyaw < math.pi / 2.0
if switch:
direction *= -1
if direction != 1.0:
speed_profile[i] = - target_speed
else:
speed_profile[i] = target_speed
if switch:
speed_profile[i] = 0.0
# speed down
for i in range(40):
speed_profile[-i] = target_speed / (50 - i)
if speed_profile[-i] <= 1.0 / 3.6:
speed_profile[-i] = 1.0 / 3.6
return speed_profile
def main():
print("LQR steering control tracking start!!")
ax = [0.0, 6.0, 12.5, 10.0, 17.5, 20.0, 25.0]
ay = [0.0, -3.0, -5.0, 6.5, 3.0, 0.0, 0.0]
goal = [ax[-1], ay[-1]]
cx, cy, cyaw, ck, s = cubic_spline_planner.calc_spline_course(
ax, ay, ds=0.1)
target_speed = 10.0 / 3.6 # simulation parameter km/h -> m/s
sp = calc_speed_profile(cyaw, target_speed)
t, x, y, yaw, v = do_simulation(cx, cy, cyaw, ck, sp, goal)
if show_animation: # pragma: no cover
plt.close()
plt.subplots(1)
plt.plot(ax, ay, "xb", label="waypoints")
plt.plot(cx, cy, "-r", label="target course")
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(t, np.array(v)*3.6, label="speed")
plt.grid(True)
plt.xlabel("Time [sec]")
plt.ylabel("Speed [m/s]")
plt.legend()
plt.subplots(1)
plt.plot(s, [np.rad2deg(iyaw) for iyaw in cyaw], "-r", label="yaw")
plt.grid(True)
plt.legend()
plt.xlabel("line length[m]")
plt.ylabel("yaw angle[deg]")
plt.subplots(1)
plt.plot(s, ck, "-r", label="curvature")
plt.grid(True)
plt.legend()
plt.xlabel("line length[m]")
plt.ylabel("curvature [1/m]")
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,652 |
```python
"""
Path tracking simulation with Stanley steering control and PID speed control.
author: Atsushi Sakai (@Atsushi_twi)
Ref:
- [Stanley: The robot that won the DARPA grand challenge](path_to_url
- [Autonomous Automobile Path Tracking](path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
import sys
import pathlib
from utils.angle import angle_mod
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
from PathPlanning.CubicSpline import cubic_spline_planner
k = 0.5 # control gain
Kp = 1.0 # speed proportional gain
dt = 0.1 # [s] time difference
L = 2.9 # [m] Wheel base of vehicle
max_steer = np.radians(30.0) # [rad] max steering angle
show_animation = True
class State:
"""
Class representing the state of a vehicle.
:param x: (float) x-coordinate
:param y: (float) y-coordinate
:param yaw: (float) yaw angle
:param v: (float) speed
"""
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
"""Instantiate the object."""
super().__init__()
self.x = x
self.y = y
self.yaw = yaw
self.v = v
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
def pid_control(target, current):
"""
Proportional control for the speed.
:param target: (float)
:param current: (float)
:return: (float)
"""
return Kp * (target - current)
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
def normalize_angle(angle):
"""
Normalize an angle to [-pi, pi].
:param angle: (float)
:return: (float) Angle in radian in [-pi, pi]
"""
return angle_mod(angle)
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
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()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathTracking/stanley_controller/stanley_controller.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,607 |
```python
"""
Path tracking simulation with rear wheel feedback steering control and PID speed control.
author: Atsushi Sakai(@Atsushi_twi)
"""
import matplotlib.pyplot as plt
import math
import numpy as np
from utils.angle import angle_mod
from scipy import interpolate
from scipy import optimize
Kp = 1.0 # speed proportional gain
# steering control parameter
KTH = 1.0
KE = 0.5
dt = 0.1 # [s]
L = 2.9 # [m]
show_animation = True
class State:
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
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
class CubicSplinePath:
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]
def calc_yaw(self, s):
dx, dy = self.dX(s), self.dY(s)
return np.arctan2(dy, dx)
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))
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
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
def pid_control(target, current):
a = Kp * (target - current)
return a
def pi_2_pi(angle):
return angle_mod(angle)
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
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(f"speed[km/h]:{round(state.v * 3.6, 2):.2f}, target s-param:{s0:.2f}")
plt.pause(0.0001)
return t, x, y, yaw, v, goal_flag
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
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()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,978 |
```python
"""
Nonlinear MPC simulation with CGMRES
author Atsushi Sakai (@Atsushi_twi)
Ref:
Shunichi09/nonlinear_control: Implementing the nonlinear model predictive
control, sliding mode control path_to_url
"""
from math import cos, sin, radians, atan2
import matplotlib.pyplot as plt
import numpy as np
U_A_MAX = 1.0
U_OMEGA_MAX = radians(45.0)
PHI_V = 0.01
PHI_OMEGA = 0.01
WB = 0.25 # [m] wheel base
show_animation = True
def differential_model(v, yaw, u_1, u_2):
dx = cos(yaw) * v
dy = sin(yaw) * v
dv = u_1
# tangent is not good for nonlinear optimization
d_yaw = v / WB * sin(u_2)
return dx, dy, d_yaw, dv
class TwoWheeledSystem:
def __init__(self, init_x, init_y, init_yaw, init_v):
self.x = init_x
self.y = init_y
self.yaw = init_yaw
self.v = init_v
self.history_x = [init_x]
self.history_y = [init_y]
self.history_yaw = [init_yaw]
self.history_v = [init_v]
def update_state(self, u_1, u_2, dt=0.01):
dx, dy, d_yaw, dv = differential_model(self.v, self.yaw, u_1, u_2)
self.x += dt * dx
self.y += dt * dy
self.yaw += dt * d_yaw
self.v += dt * dv
# save
self.history_x.append(self.x)
self.history_y.append(self.y)
self.history_yaw.append(self.yaw)
self.history_v.append(self.v)
class NMPCSimulatorSystem:
def calc_predict_and_adjoint_state(self, x, y, yaw, v, u_1s, u_2s, N, dt):
# by using state equation
x_s, y_s, yaw_s, v_s = self._calc_predict_states(
x, y, yaw, v, u_1s, u_2s, N, dt)
# by using adjoint equation
lam_1s, lam_2s, lam_3s, lam_4s = self._calc_adjoint_states(
x_s, y_s, yaw_s, v_s, u_2s, N, dt)
return x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s
def _calc_predict_states(self, x, y, yaw, v, u_1s, u_2s, N, dt):
x_s = [x]
y_s = [y]
yaw_s = [yaw]
v_s = [v]
for i in range(N):
temp_x_1, temp_x_2, temp_x_3, temp_x_4 = self._predict_state_with_oylar(
x_s[i], y_s[i], yaw_s[i], v_s[i], u_1s[i], u_2s[i], dt)
x_s.append(temp_x_1)
y_s.append(temp_x_2)
yaw_s.append(temp_x_3)
v_s.append(temp_x_4)
return x_s, y_s, yaw_s, v_s
def _calc_adjoint_states(self, x_s, y_s, yaw_s, v_s, u_2s, N, dt):
lam_1s = [x_s[-1]]
lam_2s = [y_s[-1]]
lam_3s = [yaw_s[-1]]
lam_4s = [v_s[-1]]
# backward adjoint state calc
for i in range(N - 1, 0, -1):
temp_lam_1, temp_lam_2, temp_lam_3, temp_lam_4 = self._adjoint_state_with_oylar(
yaw_s[i], v_s[i], lam_1s[0], lam_2s[0], lam_3s[0], lam_4s[0],
u_2s[i], dt)
lam_1s.insert(0, temp_lam_1)
lam_2s.insert(0, temp_lam_2)
lam_3s.insert(0, temp_lam_3)
lam_4s.insert(0, temp_lam_4)
return lam_1s, lam_2s, lam_3s, lam_4s
@staticmethod
def _predict_state_with_oylar(x, y, yaw, v, u_1, u_2, dt):
dx, dy, dyaw, dv = differential_model(
v, yaw, u_1, u_2)
next_x_1 = x + dt * dx
next_x_2 = y + dt * dy
next_x_3 = yaw + dt * dyaw
next_x_4 = v + dt * dv
return next_x_1, next_x_2, next_x_3, next_x_4
@staticmethod
def _adjoint_state_with_oylar(yaw, v, lam_1, lam_2, lam_3, lam_4, u_2, dt):
# H/x
pre_lam_1 = lam_1 + dt * 0.0
pre_lam_2 = lam_2 + dt * 0.0
tmp1 = - lam_1 * sin(yaw) * v + lam_2 * cos(yaw) * v
pre_lam_3 = lam_3 + dt * tmp1
tmp2 = lam_1 * cos(yaw) + lam_2 * sin(yaw) + lam_3 * sin(u_2) / WB
pre_lam_4 = lam_4 + dt * tmp2
return pre_lam_1, pre_lam_2, pre_lam_3, pre_lam_4
class NMPCControllerCGMRES:
"""
Attributes
------------
zeta : float
gain of optimal answer stability
ht : float
update value of NMPC this should be decided by zeta
tf : float
predict time
alpha : float
gain of predict time
N : int
predict step, discrete value
threshold : float
cgmres's threshold value
input_num : int
system input length, this should include dummy u and constraint variables
max_iteration : int
decide by the solved matrix size
simulator : NMPCSimulatorSystem class
u_1s : list of float
estimated optimal system input
u_2s : list of float
estimated optimal system input
dummy_u_1s : list of float
estimated dummy input
dummy_u_2s : list of float
estimated dummy input
raw_1s : list of float
estimated constraint variable
raw_2s : list of float
estimated constraint variable
history_u_1 : list of float
time history of actual system input
history_u_2 : list of float
time history of actual system input
history_dummy_u_1 : list of float
time history of actual dummy u_1
history_dummy_u_2 : list of float
time history of actual dummy u_2
history_raw_1 : list of float
time history of actual raw_1
history_raw_2 : list of float
time history of actual raw_2
history_f : list of float
time history of error of optimal
"""
def __init__(self):
# parameters
self.zeta = 100. # stability gain
self.ht = 0.01 # difference approximation tick
self.tf = 3.0 # final time
self.alpha = 0.5 # time gain
self.N = 10 # division number
self.threshold = 0.001
self.input_num = 6 # input number of dummy, constraints
self.max_iteration = self.input_num * self.N
# simulator
self.simulator = NMPCSimulatorSystem()
# initial input, initialize as 1.0
self.u_1s = np.ones(self.N)
self.u_2s = np.ones(self.N)
self.dummy_u_1s = np.ones(self.N)
self.dummy_u_2s = np.ones(self.N)
self.raw_1s = np.zeros(self.N)
self.raw_2s = np.zeros(self.N)
self.history_u_1 = []
self.history_u_2 = []
self.history_dummy_u_1 = []
self.history_dummy_u_2 = []
self.history_raw_1 = []
self.history_raw_2 = []
self.history_f = []
def calc_input(self, x, y, yaw, v, time):
# calculating sampling time
dt = self.tf * (1. - np.exp(-self.alpha * time)) / float(self.N)
# x_dot
x_1_dot, x_2_dot, x_3_dot, x_4_dot = differential_model(
v, yaw, self.u_1s[0], self.u_2s[0])
dx_1 = x_1_dot * self.ht
dx_2 = x_2_dot * self.ht
dx_3 = x_3_dot * self.ht
dx_4 = x_4_dot * self.ht
x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s = self.simulator.calc_predict_and_adjoint_state(
x + dx_1, y + dx_2, yaw + dx_3, v + dx_4, self.u_1s, self.u_2s,
self.N, dt)
# Fxt:F(U,x+hx,t+h)
Fxt = self._calc_f(v_s, lam_3s, lam_4s,
self.u_1s, self.u_2s, self.dummy_u_1s,
self.dummy_u_2s,
self.raw_1s, self.raw_2s, self.N)
# F:F(U,x,t)
x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s = self.simulator.calc_predict_and_adjoint_state(
x, y, yaw, v, self.u_1s, self.u_2s, self.N, dt)
F = self._calc_f(v_s, lam_3s, lam_4s,
self.u_1s, self.u_2s, self.dummy_u_1s, self.dummy_u_2s,
self.raw_1s, self.raw_2s, self.N)
right = -self.zeta * F - ((Fxt - F) / self.ht)
du_1 = self.u_1s * self.ht
du_2 = self.u_2s * self.ht
ddummy_u_1 = self.dummy_u_1s * self.ht
ddummy_u_2 = self.dummy_u_2s * self.ht
draw_1 = self.raw_1s * self.ht
draw_2 = self.raw_2s * self.ht
x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s = self.simulator.calc_predict_and_adjoint_state(
x + dx_1, y + dx_2, yaw + dx_3, v + dx_4, self.u_1s + du_1,
self.u_2s + du_2, self.N, dt)
# Fuxt:F(U+hdU(0),x+hx,t+h)
Fuxt = self._calc_f(v_s, lam_3s, lam_4s,
self.u_1s + du_1, self.u_2s + du_2,
self.dummy_u_1s + ddummy_u_1,
self.dummy_u_2s + ddummy_u_2,
self.raw_1s + draw_1, self.raw_2s + draw_2, self.N)
left = ((Fuxt - Fxt) / self.ht)
# calculating cgmres
r0 = right - left
r0_norm = np.linalg.norm(r0)
vs = np.zeros((self.max_iteration, self.max_iteration + 1))
vs[:, 0] = r0 / r0_norm
hs = np.zeros((self.max_iteration + 1, self.max_iteration + 1))
# in this case the state is 3(u and dummy_u)
e = np.zeros((self.max_iteration + 1, 1))
e[0] = 1.0
ys_pre = None
du_1_new, du_2_new, draw_1_new, draw_2_new = None, None, None, None
ddummy_u_1_new, ddummy_u_2_new = None, None
for i in range(self.max_iteration):
du_1 = vs[::self.input_num, i] * self.ht
du_2 = vs[1::self.input_num, i] * self.ht
ddummy_u_1 = vs[2::self.input_num, i] * self.ht
ddummy_u_2 = vs[3::self.input_num, i] * self.ht
draw_1 = vs[4::self.input_num, i] * self.ht
draw_2 = vs[5::self.input_num, i] * self.ht
x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s = self.simulator.calc_predict_and_adjoint_state(
x + dx_1, y + dx_2, yaw + dx_3, v + dx_4, self.u_1s + du_1,
self.u_2s + du_2, self.N, dt)
Fuxt = self._calc_f(v_s, lam_3s, lam_4s,
self.u_1s + du_1, self.u_2s + du_2,
self.dummy_u_1s + ddummy_u_1,
self.dummy_u_2s + ddummy_u_2,
self.raw_1s + draw_1, self.raw_2s + draw_2,
self.N)
Av = ((Fuxt - Fxt) / self.ht)
sum_Av = np.zeros(self.max_iteration)
# GramSchmidt orthonormalization
for j in range(i + 1):
hs[j, i] = np.dot(Av, vs[:, j])
sum_Av = sum_Av + hs[j, i] * vs[:, j]
v_est = Av - sum_Av
hs[i + 1, i] = np.linalg.norm(v_est)
vs[:, i + 1] = v_est / hs[i + 1, i]
inv_hs = np.linalg.pinv(hs[:i + 1, :i])
ys = np.dot(inv_hs, r0_norm * e[:i + 1])
judge_value = r0_norm * e[:i + 1] - np.dot(hs[:i + 1, :i], ys[:i])
flag1 = np.linalg.norm(judge_value) < self.threshold
flag2 = i == self.max_iteration - 1
if flag1 or flag2:
update_val = np.dot(vs[:, :i - 1], ys_pre[:i - 1]).flatten()
du_1_new = du_1 + update_val[::self.input_num]
du_2_new = du_2 + update_val[1::self.input_num]
ddummy_u_1_new = ddummy_u_1 + update_val[2::self.input_num]
ddummy_u_2_new = ddummy_u_2 + update_val[3::self.input_num]
draw_1_new = draw_1 + update_val[4::self.input_num]
draw_2_new = draw_2 + update_val[5::self.input_num]
break
ys_pre = ys
# update input
self.u_1s += du_1_new * self.ht
self.u_2s += du_2_new * self.ht
self.dummy_u_1s += ddummy_u_1_new * self.ht
self.dummy_u_2s += ddummy_u_2_new * self.ht
self.raw_1s += draw_1_new * self.ht
self.raw_2s += draw_2_new * self.ht
x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s = self.simulator.calc_predict_and_adjoint_state(
x, y, yaw, v, self.u_1s, self.u_2s, self.N, dt)
F = self._calc_f(v_s, lam_3s, lam_4s,
self.u_1s, self.u_2s, self.dummy_u_1s, self.dummy_u_2s,
self.raw_1s, self.raw_2s, self.N)
print("norm(F) = {0}".format(np.linalg.norm(F)))
# for save
self.history_f.append(np.linalg.norm(F))
self.history_u_1.append(self.u_1s[0])
self.history_u_2.append(self.u_2s[0])
self.history_dummy_u_1.append(self.dummy_u_1s[0])
self.history_dummy_u_2.append(self.dummy_u_2s[0])
self.history_raw_1.append(self.raw_1s[0])
self.history_raw_2.append(self.raw_2s[0])
return self.u_1s, self.u_2s
@staticmethod
def _calc_f(v_s, lam_3s, lam_4s, u_1s, u_2s, dummy_u_1s, dummy_u_2s,
raw_1s, raw_2s, N):
F = []
for i in range(N):
# H/u(xi, ui, i)
F.append(u_1s[i] + lam_4s[i] + 2.0 * raw_1s[i] * u_1s[i])
F.append(u_2s[i] + lam_3s[i] * v_s[i] /
WB * cos(u_2s[i]) ** 2 + 2.0 * raw_2s[i] * u_2s[i])
F.append(-PHI_V + 2.0 * raw_1s[i] * dummy_u_1s[i])
F.append(-PHI_OMEGA + 2.0 * raw_2s[i] * dummy_u_2s[i])
# C(xi, ui, i)
F.append(u_1s[i] ** 2 + dummy_u_1s[i] ** 2 - U_A_MAX ** 2)
F.append(u_2s[i] ** 2 + dummy_u_2s[i] ** 2 - U_OMEGA_MAX ** 2)
return np.array(F)
def plot_figures(plant_system, controller, iteration_num,
dt): # pragma: no cover
# figure
# time history
fig_p = plt.figure()
fig_u = plt.figure()
fig_f = plt.figure()
# trajectory
fig_t = plt.figure()
fig_trajectory = fig_t.add_subplot(111)
fig_trajectory.set_aspect('equal')
x_1_fig = fig_p.add_subplot(411)
x_2_fig = fig_p.add_subplot(412)
x_3_fig = fig_p.add_subplot(413)
x_4_fig = fig_p.add_subplot(414)
u_1_fig = fig_u.add_subplot(411)
u_2_fig = fig_u.add_subplot(412)
dummy_1_fig = fig_u.add_subplot(413)
dummy_2_fig = fig_u.add_subplot(414)
raw_1_fig = fig_f.add_subplot(311)
raw_2_fig = fig_f.add_subplot(312)
f_fig = fig_f.add_subplot(313)
x_1_fig.plot(np.arange(iteration_num) * dt, plant_system.history_x)
x_1_fig.set_xlabel("time [s]")
x_1_fig.set_ylabel("x")
x_2_fig.plot(np.arange(iteration_num) * dt, plant_system.history_y)
x_2_fig.set_xlabel("time [s]")
x_2_fig.set_ylabel("y")
x_3_fig.plot(np.arange(iteration_num) * dt, plant_system.history_yaw)
x_3_fig.set_xlabel("time [s]")
x_3_fig.set_ylabel("yaw")
x_4_fig.plot(np.arange(iteration_num) * dt, plant_system.history_v)
x_4_fig.set_xlabel("time [s]")
x_4_fig.set_ylabel("v")
u_1_fig.plot(np.arange(iteration_num - 1) * dt, controller.history_u_1)
u_1_fig.set_xlabel("time [s]")
u_1_fig.set_ylabel("u_a")
u_2_fig.plot(np.arange(iteration_num - 1) * dt, controller.history_u_2)
u_2_fig.set_xlabel("time [s]")
u_2_fig.set_ylabel("u_omega")
dummy_1_fig.plot(np.arange(iteration_num - 1) *
dt, controller.history_dummy_u_1)
dummy_1_fig.set_xlabel("time [s]")
dummy_1_fig.set_ylabel("dummy u_1")
dummy_2_fig.plot(np.arange(iteration_num - 1) *
dt, controller.history_dummy_u_2)
dummy_2_fig.set_xlabel("time [s]")
dummy_2_fig.set_ylabel("dummy u_2")
raw_1_fig.plot(np.arange(iteration_num - 1) * dt, controller.history_raw_1)
raw_1_fig.set_xlabel("time [s]")
raw_1_fig.set_ylabel("raw_1")
raw_2_fig.plot(np.arange(iteration_num - 1) * dt, controller.history_raw_2)
raw_2_fig.set_xlabel("time [s]")
raw_2_fig.set_ylabel("raw_2")
f_fig.plot(np.arange(iteration_num - 1) * dt, controller.history_f)
f_fig.set_xlabel("time [s]")
f_fig.set_ylabel("optimal error")
fig_trajectory.plot(plant_system.history_x,
plant_system.history_y, "-r")
fig_trajectory.set_xlabel("x [m]")
fig_trajectory.set_ylabel("y [m]")
fig_trajectory.axis("equal")
# start state
plot_car(plant_system.history_x[0],
plant_system.history_y[0],
plant_system.history_yaw[0],
controller.history_u_2[0],
)
# goal state
plot_car(0.0, 0.0, 0.0, 0.0)
plt.show()
def plot_car(x, y, yaw, steer=0.0, truck_color="-k"): # pragma: no cover
# Vehicle parameters
LENGTH = 0.4 # [m]
WIDTH = 0.2 # [m]
BACK_TO_WHEEL = 0.1 # [m]
WHEEL_LEN = 0.03 # [m]
WHEEL_WIDTH = 0.02 # [m]
TREAD = 0.07 # [m]
outline = np.array(
[[-BACK_TO_WHEEL, (LENGTH - BACK_TO_WHEEL), (LENGTH - BACK_TO_WHEEL),
-BACK_TO_WHEEL, -BACK_TO_WHEEL],
[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([[cos(yaw), sin(yaw)],
[-sin(yaw), cos(yaw)]])
Rot2 = np.array([[cos(steer), sin(steer)],
[-sin(steer), 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(), truck_color)
plt.plot(np.array(fr_wheel[0, :]).flatten(),
np.array(fr_wheel[1, :]).flatten(), truck_color)
plt.plot(np.array(rr_wheel[0, :]).flatten(),
np.array(rr_wheel[1, :]).flatten(), truck_color)
plt.plot(np.array(fl_wheel[0, :]).flatten(),
np.array(fl_wheel[1, :]).flatten(), truck_color)
plt.plot(np.array(rl_wheel[0, :]).flatten(),
np.array(rl_wheel[1, :]).flatten(), truck_color)
plt.plot(x, y, "*")
def animation(plant, controller, dt):
skip = 2 # skip index for animation
for t in range(1, len(controller.history_u_1), skip):
x = plant.history_x[t]
y = plant.history_y[t]
yaw = plant.history_yaw[t]
v = plant.history_v[t]
accel = controller.history_u_1[t]
time = t * dt
if abs(v) <= 0.01:
steer = 0.0
else:
steer = atan2(controller.history_u_2[t] * WB / v, 1.0)
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(plant.history_x, plant.history_y, "-r", label="trajectory")
plot_car(x, y, yaw, steer=steer)
plt.axis("equal")
plt.grid(True)
plt.title("Time[s]:" + str(round(time, 2)) +
", accel[m/s]:" + str(round(accel, 2)) +
", speed[km/h]:" + str(round(v * 3.6, 2)))
plt.pause(0.0001)
plt.close("all")
def main():
# simulation time
dt = 0.1
iteration_time = 150.0 # [s]
init_x = -4.5
init_y = -2.5
init_yaw = radians(45.0)
init_v = -1.0
# plant
plant_system = TwoWheeledSystem(
init_x, init_y, init_yaw, init_v)
# controller
controller = NMPCControllerCGMRES()
iteration_num = int(iteration_time / dt)
for i in range(1, iteration_num):
time = float(i) * dt
# make input
u_1s, u_2s = controller.calc_input(
plant_system.x, plant_system.y, plant_system.yaw, plant_system.v,
time)
# update state
plant_system.update_state(u_1s[0], u_2s[0])
if show_animation: # pragma: no cover
animation(plant_system, controller, dt)
plot_figures(plant_system, controller, iteration_num, dt)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/PathTracking/cgmres_nmpc/cgmres_nmpc.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 6,475 |
```batchfile
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
set SPHINXPROJ=PythonRobotics
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.path_to_url
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
``` | /content/code_sandbox/docs/make.bat | batchfile | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 262 |
```python
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# path_to_url
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../'))
# -- Project information -----------------------------------------------------
project = 'PythonRobotics'
copyright = '2018-2023, Atsushi Sakai'
author = 'Atsushi Sakai'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = ''
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'matplotlib.sphinxext.plot_directive',
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
'sphinx.ext.imgconverter',
'IPython.sphinxext.ipython_console_highlighting',
'sphinx_copybutton',
'sphinx_rtd_dark_mode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '_main.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# Fix for read the docs
on_rtd = os.environ.get('READTHEDOCS') == 'True'
if on_rtd:
html_theme = 'default'
else:
html_theme = 'sphinx_rtd_light_them'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_logo = '../icon.png'
html_theme_options = {
'display_version': False,
}
# replace "view page source" with "edit on github" in Read The Docs theme
# * path_to_url
html_context = {
'display_github': True,
'github_user': 'AtsushiSakai',
'github_repo': 'PythonRobotics',
'github_version': 'master',
"conf_py_path": "/docs/",
"source_suffix": source_suffix,
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = ['custom.css']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'PythonRoboticsdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PythonRobotics.tex', 'PythonRobotics Documentation',
'Atsushi Sakai', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pythonrobotics', 'PythonRobotics Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PythonRobotics', 'PythonRobotics Documentation',
author, 'PythonRobotics', 'One line description of project.',
'Miscellaneous'),
]
# -- Extension configuration -------------------------------------------------
``` | /content/code_sandbox/docs/conf.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,298 |
```html
{% extends "!layout.html" %}
{% block sidebartitle %}
{{ super() }}
<script async src="path_to_url"
crossorigin="anonymous"></script>
<!-- PythonRoboticsDoc -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-9612347954373886"
data-ad-slot="1579532132"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
{% endblock %}
``` | /content/code_sandbox/docs/_templates/layout.html | html | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 120 |
```css
/*
* Necessary parts from
* Sphinx stylesheet -- basic theme
* absent from sphinx_rtd_theme
* (see path_to_url
* Ref path_to_url
*/
/* -- math display ---------------------------------------------------------- */
span.eqno {
float: right;
}
span.eqno a.headerlink {
position: absolute;
z-index: 1;
visibility: hidden;
}
div.math:hover a.headerlink {
visibility: visible;
}
``` | /content/code_sandbox/docs/_static/custom.css | css | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 92 |
```python
"""
Quintic Polynomials Planner
author: Atsushi Sakai (@Atsushi_twi)
Ref:
- [Local Path planning And Motion Control For Agv In Positioning](path_to_url
"""
import math
import matplotlib.pyplot as plt
import numpy as np
# parameter
MAX_T = 100.0 # maximum time to the goal [s]
MIN_T = 5.0 # minimum time to the goal[s]
show_animation = True
class QuinticPolynomial:
def __init__(self, xs, vxs, axs, xe, vxe, axe, time):
# calc coefficient of quintic polynomial
# See jupyter notebook document for derivation of this equation.
self.a0 = xs
self.a1 = vxs
self.a2 = axs / 2.0
A = np.array([[time ** 3, time ** 4, time ** 5],
[3 * time ** 2, 4 * time ** 3, 5 * time ** 4],
[6 * time, 12 * time ** 2, 20 * time ** 3]])
b = np.array([xe - self.a0 - self.a1 * time - self.a2 * time ** 2,
vxe - self.a1 - 2 * self.a2 * time,
axe - 2 * self.a2])
x = np.linalg.solve(A, b)
self.a3 = x[0]
self.a4 = x[1]
self.a5 = x[2]
def calc_point(self, t):
xt = self.a0 + self.a1 * t + self.a2 * t ** 2 + \
self.a3 * t ** 3 + self.a4 * t ** 4 + self.a5 * t ** 5
return xt
def calc_first_derivative(self, t):
xt = self.a1 + 2 * self.a2 * t + \
3 * self.a3 * t ** 2 + 4 * self.a4 * t ** 3 + 5 * self.a5 * t ** 4
return xt
def calc_second_derivative(self, t):
xt = 2 * self.a2 + 6 * self.a3 * t + 12 * self.a4 * t ** 2 + 20 * self.a5 * t ** 3
return xt
def calc_third_derivative(self, t):
xt = 6 * self.a3 + 24 * self.a4 * t + 60 * self.a5 * t ** 2
return xt
def quintic_polynomials_planner(sx, sy, syaw, sv, sa, gx, gy, gyaw, gv, ga, max_accel, max_jerk, dt):
"""
quintic polynomial planner
input
s_x: start x position [m]
s_y: start y position [m]
s_yaw: start yaw angle [rad]
sa: start accel [m/ss]
gx: goal x position [m]
gy: goal y position [m]
gyaw: goal yaw angle [rad]
ga: goal accel [m/ss]
max_accel: maximum accel [m/ss]
max_jerk: maximum jerk [m/sss]
dt: time tick [s]
return
time: time result
rx: x position result list
ry: y position result list
ryaw: yaw angle result list
rv: velocity result list
ra: accel result list
"""
vxs = sv * math.cos(syaw)
vys = sv * math.sin(syaw)
vxg = gv * math.cos(gyaw)
vyg = gv * math.sin(gyaw)
axs = sa * math.cos(syaw)
ays = sa * math.sin(syaw)
axg = ga * math.cos(gyaw)
ayg = ga * math.sin(gyaw)
time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], []
for T in np.arange(MIN_T, MAX_T, MIN_T):
xqp = QuinticPolynomial(sx, vxs, axs, gx, vxg, axg, T)
yqp = QuinticPolynomial(sy, vys, ays, gy, vyg, ayg, T)
time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], []
for t in np.arange(0.0, T + dt, dt):
time.append(t)
rx.append(xqp.calc_point(t))
ry.append(yqp.calc_point(t))
vx = xqp.calc_first_derivative(t)
vy = yqp.calc_first_derivative(t)
v = np.hypot(vx, vy)
yaw = math.atan2(vy, vx)
rv.append(v)
ryaw.append(yaw)
ax = xqp.calc_second_derivative(t)
ay = yqp.calc_second_derivative(t)
a = np.hypot(ax, ay)
if len(rv) >= 2 and rv[-1] - rv[-2] < 0.0:
a *= -1
ra.append(a)
jx = xqp.calc_third_derivative(t)
jy = yqp.calc_third_derivative(t)
j = np.hypot(jx, jy)
if len(ra) >= 2 and ra[-1] - ra[-2] < 0.0:
j *= -1
rj.append(j)
if max([abs(i) for i in ra]) <= max_accel and max([abs(i) for i in rj]) <= max_jerk:
print("find path!!")
break
if show_animation: # pragma: no cover
for i, _ in enumerate(time):
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.grid(True)
plt.axis("equal")
plot_arrow(sx, sy, syaw)
plot_arrow(gx, gy, gyaw)
plot_arrow(rx[i], ry[i], ryaw[i])
plt.title("Time[s]:" + str(time[i])[0:4] +
" v[m/s]:" + str(rv[i])[0:4] +
" a[m/ss]:" + str(ra[i])[0:4] +
" jerk[m/sss]:" + str(rj[i])[0:4],
)
plt.pause(0.001)
return time, rx, ry, ryaw, rv, ra, rj
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): # pragma: no cover
"""
Plot arrow
"""
if not isinstance(x, float):
for (ix, iy, iyaw) in zip(x, y, yaw):
plot_arrow(ix, iy, iyaw)
else:
plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
fc=fc, ec=ec, head_width=width, head_length=width)
plt.plot(x, y)
def main():
print(__file__ + " start!!")
sx = 10.0 # start x position [m]
sy = 10.0 # start y position [m]
syaw = np.deg2rad(10.0) # start yaw angle [rad]
sv = 1.0 # start speed [m/s]
sa = 0.1 # start accel [m/ss]
gx = 30.0 # goal x position [m]
gy = -10.0 # goal y position [m]
gyaw = np.deg2rad(20.0) # goal yaw angle [rad]
gv = 1.0 # goal speed [m/s]
ga = 0.1 # goal accel [m/ss]
max_accel = 1.0 # max accel [m/ss]
max_jerk = 0.5 # max jerk [m/sss]
dt = 0.1 # time tick [s]
time, x, y, yaw, v, a, j = quintic_polynomials_planner(
sx, sy, syaw, sv, sa, gx, gy, gyaw, gv, ga, max_accel, max_jerk, dt)
if show_animation: # pragma: no cover
plt.plot(x, y, "-r")
plt.subplots()
plt.plot(time, [np.rad2deg(i) for i in yaw], "-r")
plt.xlabel("Time[s]")
plt.ylabel("Yaw[deg]")
plt.grid(True)
plt.subplots()
plt.plot(time, v, "-r")
plt.xlabel("Time[s]")
plt.ylabel("Speed[m/s]")
plt.grid(True)
plt.subplots()
plt.plot(time, a, "-r")
plt.xlabel("Time[s]")
plt.ylabel("accel[m/ss]")
plt.grid(True)
plt.subplots()
plt.plot(time, j, "-r")
plt.xlabel("Time[s]")
plt.ylabel("jerk[m/sss]")
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/QuinticPolynomialsPlanner/quintic_polynomials_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,054 |
```python
"""
Potential Field based path planner
author: Atsushi Sakai (@Atsushi_twi)
Ref:
path_to_url~motionplanning/lecture/Chap4-Potential-Field_howie.pdf
"""
from collections import deque
import numpy as np
import matplotlib.pyplot as plt
# Parameters
KP = 5.0 # attractive potential gain
ETA = 100.0 # repulsive potential gain
AREA_WIDTH = 30.0 # potential area width [m]
# the number of previous positions used to check oscillations
OSCILLATIONS_DETECTION_LENGTH = 3
show_animation = True
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
def calc_attractive_potential(x, y, gx, gy):
return 0.5 * KP * np.hypot(x - gx, y - gy)
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
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
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
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
def draw_heatmap(data):
data = np.array(data).T
plt.pcolor(data, vmax=100.0, cmap=plt.cm.Blues)
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()
if __name__ == '__main__':
print(__file__ + " start!!")
main()
print(__file__ + " Done!!")
``` | /content/code_sandbox/PathPlanning/PotentialFieldPlanning/potential_field_planning.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,591 |
```python
"""
Path planning Sample Code with RRT and Dubins path
author: AtsushiSakai(@Atsushi_twi)
"""
import copy
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent)) # root dir
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from DubinsPath import dubins_path_planner
from RRTStar.rrt_star import RRTStar
from utils.plot import plot_arrow
show_animation = True
class RRTStarDubins(RRTStar):
"""
Class for RRT star planning with Dubins path
"""
class Node(RRTStar.Node):
"""
RRT Node
"""
def __init__(self, x, y, yaw):
super().__init__(x, y)
self.yaw = yaw
self.path_yaw = []
def __init__(self, start, goal, obstacle_list, rand_area,
goal_sample_rate=10,
max_iter=200,
connect_circle_dist=50.0,
robot_radius=0.0,
):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1], start[2])
self.end = self.Node(goal[0], goal[1], goal[2])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.connect_circle_dist = connect_circle_dist
self.curvature = 1.0 # for dubins path
self.goal_yaw_th = np.deg2rad(1.0)
self.goal_xy_th = 0.5
self.robot_radius = robot_radius
def planning(self, animation=True, search_until_max_iter=True):
"""
RRT Star planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind], rnd)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
near_indexes = self.find_near_nodes(new_node)
new_node = self.choose_parent(new_node, near_indexes)
if new_node:
self.node_list.append(new_node)
self.rewire(new_node, near_indexes)
if animation and i % 5 == 0:
self.plot_start_goal_arrow()
self.draw_graph(rnd)
if (not search_until_max_iter) and new_node: # check reaching the goal
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
else:
print("Cannot find path")
return None
def draw_graph(self, rnd=None):
plt.clf()
# 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 rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
self.plot_start_goal_arrow()
plt.pause(0.01)
def plot_start_goal_arrow(self):
plot_arrow(self.start.x, self.start.y, self.start.yaw)
plot_arrow(self.end.x, self.end.y, self.end.yaw)
def steer(self, from_node, to_node):
px, py, pyaw, mode, course_lengths = \
dubins_path_planner.plan_dubins_path(
from_node.x, from_node.y, from_node.yaw,
to_node.x, to_node.y, to_node.yaw, self.curvature)
if len(px) <= 1: # cannot find a dubins path
return None
new_node = copy.deepcopy(from_node)
new_node.x = px[-1]
new_node.y = py[-1]
new_node.yaw = pyaw[-1]
new_node.path_x = px
new_node.path_y = py
new_node.path_yaw = pyaw
new_node.cost += sum([abs(c) for c in course_lengths])
new_node.parent = from_node
return new_node
def calc_new_cost(self, from_node, to_node):
_, _, _, _, course_lengths = dubins_path_planner.plan_dubins_path(
from_node.x, from_node.y, from_node.yaw,
to_node.x, to_node.y, to_node.yaw, self.curvature)
cost = sum([abs(c) for c in course_lengths])
return from_node.cost + cost
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand),
random.uniform(-math.pi, math.pi)
)
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y, self.end.yaw)
return rnd
def search_best_goal_node(self):
goal_indexes = []
for (i, node) in enumerate(self.node_list):
if self.calc_dist_to_goal(node.x, node.y) <= self.goal_xy_th:
goal_indexes.append(i)
# angle check
final_goal_indexes = []
for i in goal_indexes:
if abs(self.node_list[i].yaw - self.end.yaw) <= self.goal_yaw_th:
final_goal_indexes.append(i)
if not final_goal_indexes:
return None
min_cost = min([self.node_list[i].cost for i in final_goal_indexes])
for i in final_goal_indexes:
if self.node_list[i].cost == min_cost:
return i
return None
def generate_final_course(self, goal_index):
print("final")
path = [[self.end.x, self.end.y]]
node = self.node_list[goal_index]
while node.parent:
for (ix, iy) in zip(reversed(node.path_x), reversed(node.path_y)):
path.append([ix, iy])
node = node.parent
path.append([self.start.x, self.start.y])
return path
def main():
print("Start rrt star with dubins planning")
# ====Search Path with RRT====
obstacleList = [
(5, 5, 1),
(3, 6, 2),
(3, 8, 2),
(3, 10, 2),
(7, 5, 2),
(9, 5, 2)
] # [x,y,size(radius)]
# Set Initial parameters
start = [0.0, 0.0, np.deg2rad(0.0)]
goal = [10.0, 10.0, np.deg2rad(0.0)]
rrtstar_dubins = RRTStarDubins(start, goal, rand_area=[-2.0, 15.0], obstacle_list=obstacleList)
path = rrtstar_dubins.planning(animation=show_animation)
# Draw final path
if show_animation: # pragma: no cover
rrtstar_dubins.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRTStarDubins/rrt_star_dubins.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,881 |
```python
"""
eta^3 polynomials planner
author: Joe Dinius, Ph.D (path_to_url
Atsushi Sakai (@Atsushi_twi)
Ref:
- [eta^3-Splines for the Smooth Path Generation of Wheeled Mobile Robots]
(path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
# NOTE: *_pose is a 3-array:
# 0 - x coord, 1 - y coord, 2 - orientation angle \theta
show_animation = True
class Eta3Path(object):
"""
Eta3Path
input
segments: a list of `Eta3PathSegment` instances
defining a continuous path
"""
def __init__(self, segments):
# ensure input has the correct form
assert(isinstance(segments, list) and isinstance(
segments[0], Eta3PathSegment))
# ensure that each segment begins from the previous segment's end (continuity)
for r, s in zip(segments[:-1], segments[1:]):
assert(np.array_equal(r.end_pose, s.start_pose))
self.segments = segments
def calc_path_point(self, u):
"""
Eta3Path::calc_path_point
input
normalized interpolation point along path object, 0 <= u <= len(self.segments)
returns
2d (x,y) position vector
"""
assert(0 <= u <= len(self.segments))
if np.isclose(u, len(self.segments)):
segment_idx = len(self.segments) - 1
u = 1.
else:
segment_idx = int(np.floor(u))
u -= segment_idx
return self.segments[segment_idx].calc_point(u)
class Eta3PathSegment(object):
"""
Eta3PathSegment - constructs an eta^3 path segment based on desired
shaping, eta, and curvature vector, kappa. If either, or both,
of eta and kappa are not set during initialization,
they will default to zeros.
input
start_pose - starting pose array (x, y, \theta)
end_pose - ending pose array (x, y, \theta)
eta - shaping parameters, default=None
kappa - curvature parameters, default=None
"""
def __init__(self, start_pose, end_pose, eta=None, kappa=None):
# make sure inputs are of the correct size
assert(len(start_pose) == 3 and len(start_pose) == len(end_pose))
self.start_pose = start_pose
self.end_pose = end_pose
# if no eta is passed, initialize it to array of zeros
if not eta:
eta = np.zeros((6,))
else:
# make sure that eta has correct size
assert(len(eta) == 6)
# if no kappa is passed, initialize to array of zeros
if not kappa:
kappa = np.zeros((4,))
else:
assert(len(kappa) == 4)
# set up angle cosines and sines for simpler computations below
ca = np.cos(start_pose[2])
sa = np.sin(start_pose[2])
cb = np.cos(end_pose[2])
sb = np.sin(end_pose[2])
# 2 dimensions (x,y) x 8 coefficients per dimension
self.coeffs = np.empty((2, 8))
# constant terms (u^0)
self.coeffs[0, 0] = start_pose[0]
self.coeffs[1, 0] = start_pose[1]
# linear (u^1)
self.coeffs[0, 1] = eta[0] * ca
self.coeffs[1, 1] = eta[0] * sa
# quadratic (u^2)
self.coeffs[0, 2] = 1. / 2 * eta[2] * \
ca - 1. / 2 * eta[0]**2 * kappa[0] * sa
self.coeffs[1, 2] = 1. / 2 * eta[2] * \
sa + 1. / 2 * eta[0]**2 * kappa[0] * ca
# cubic (u^3)
self.coeffs[0, 3] = 1. / 6 * eta[4] * ca - 1. / 6 * \
(eta[0]**3 * kappa[1] + 3. * eta[0] * eta[2] * kappa[0]) * sa
self.coeffs[1, 3] = 1. / 6 * eta[4] * sa + 1. / 6 * \
(eta[0]**3 * kappa[1] + 3. * eta[0] * eta[2] * kappa[0]) * ca
# quartic (u^4)
tmp1 = 35. * (end_pose[0] - start_pose[0])
tmp2 = (20. * eta[0] + 5 * eta[2] + 2. / 3 * eta[4]) * ca
tmp3 = (5. * eta[0] ** 2 * kappa[0] + 2. / 3 * eta[0] ** 3 * kappa[1]
+ 2. * eta[0] * eta[2] * kappa[0]) * sa
tmp4 = (15. * eta[1] - 5. / 2 * eta[3] + 1. / 6 * eta[5]) * cb
tmp5 = (5. / 2 * eta[1] ** 2 * kappa[2] - 1. / 6 * eta[1] ** 3 *
kappa[3] - 1. / 2 * eta[1] * eta[3] * kappa[2]) * sb
self.coeffs[0, 4] = tmp1 - tmp2 + tmp3 - tmp4 - tmp5
tmp1 = 35. * (end_pose[1] - start_pose[1])
tmp2 = (20. * eta[0] + 5. * eta[2] + 2. / 3 * eta[4]) * sa
tmp3 = (5. * eta[0] ** 2 * kappa[0] + 2. / 3 * eta[0] ** 3 * kappa[1]
+ 2. * eta[0] * eta[2] * kappa[0]) * ca
tmp4 = (15. * eta[1] - 5. / 2 * eta[3] + 1. / 6 * eta[5]) * sb
tmp5 = (5. / 2 * eta[1] ** 2 * kappa[2] - 1. / 6 * eta[1] ** 3 *
kappa[3] - 1. / 2 * eta[1] * eta[3] * kappa[2]) * cb
self.coeffs[1, 4] = tmp1 - tmp2 - tmp3 - tmp4 + tmp5
# quintic (u^5)
tmp1 = -84. * (end_pose[0] - start_pose[0])
tmp2 = (45. * eta[0] + 10. * eta[2] + eta[4]) * ca
tmp3 = (10. * eta[0] ** 2 * kappa[0] + eta[0] ** 3 * kappa[1] + 3. *
eta[0] * eta[2] * kappa[0]) * sa
tmp4 = (39. * eta[1] - 7. * eta[3] + 1. / 2 * eta[5]) * cb
tmp5 = + (7. * eta[1] ** 2 * kappa[2] - 1. / 2 * eta[1] ** 3 * kappa[3]
- 3. / 2 * eta[1] * eta[3] * kappa[2]) * sb
self.coeffs[0, 5] = tmp1 + tmp2 - tmp3 + tmp4 + tmp5
tmp1 = -84. * (end_pose[1] - start_pose[1])
tmp2 = (45. * eta[0] + 10. * eta[2] + eta[4]) * sa
tmp3 = (10. * eta[0] ** 2 * kappa[0] + eta[0] ** 3 * kappa[1] + 3. *
eta[0] * eta[2] * kappa[0]) * ca
tmp4 = (39. * eta[1] - 7. * eta[3] + 1. / 2 * eta[5]) * sb
tmp5 = - (7. * eta[1] ** 2 * kappa[2] - 1. / 2 * eta[1] ** 3 * kappa[3]
- 3. / 2 * eta[1] * eta[3] * kappa[2]) * cb
self.coeffs[1, 5] = tmp1 + tmp2 + tmp3 + tmp4 + tmp5
# sextic (u^6)
tmp1 = 70. * (end_pose[0] - start_pose[0])
tmp2 = (36. * eta[0] + 15. / 2 * eta[2] + 2. / 3 * eta[4]) * ca
tmp3 = + (15. / 2 * eta[0] ** 2 * kappa[0] + 2. / 3 * eta[0] ** 3 *
kappa[1] + 2. * eta[0] * eta[2] * kappa[0]) * sa
tmp4 = (34. * eta[1] - 13. / 2 * eta[3] + 1. / 2 * eta[5]) * cb
tmp5 = - (13. / 2 * eta[1] ** 2 * kappa[2] - 1. / 2 * eta[1] ** 3 *
kappa[3] - 3. / 2 * eta[1] * eta[3] * kappa[2]) * sb
self.coeffs[0, 6] = tmp1 - tmp2 + tmp3 - tmp4 + tmp5
tmp1 = 70. * (end_pose[1] - start_pose[1])
tmp2 = - (36. * eta[0] + 15. / 2 * eta[2] + 2. / 3 * eta[4]) * sa
tmp3 = - (15. / 2 * eta[0] ** 2 * kappa[0] + 2. / 3 * eta[0] ** 3 *
kappa[1] + 2. * eta[0] * eta[2] * kappa[0]) * ca
tmp4 = - (34. * eta[1] - 13. / 2 * eta[3] + 1. / 2 * eta[5]) * sb
tmp5 = + (13. / 2 * eta[1] ** 2 * kappa[2] - 1. / 2 * eta[1] ** 3 *
kappa[3] - 3. / 2 * eta[1] * eta[3] * kappa[2]) * cb
self.coeffs[1, 6] = tmp1 + tmp2 + tmp3 + tmp4 + tmp5
# septic (u^7)
tmp1 = -20. * (end_pose[0] - start_pose[0])
tmp2 = (10. * eta[0] + 2. * eta[2] + 1. / 6 * eta[4]) * ca
tmp3 = - (2. * eta[0] ** 2 * kappa[0] + 1. / 6 * eta[0] ** 3 * kappa[1]
+ 1. / 2 * eta[0] * eta[2] * kappa[0]) * sa
tmp4 = (10. * eta[1] - 2. * eta[3] + 1. / 6 * eta[5]) * cb
tmp5 = (2. * eta[1] ** 2 * kappa[2] - 1. / 6 * eta[1] ** 3 * kappa[3]
- 1. / 2 * eta[1] * eta[3] * kappa[2]) * sb
self.coeffs[0, 7] = tmp1 + tmp2 + tmp3 + tmp4 + tmp5
tmp1 = -20. * (end_pose[1] - start_pose[1])
tmp2 = (10. * eta[0] + 2. * eta[2] + 1. / 6 * eta[4]) * sa
tmp3 = (2. * eta[0] ** 2 * kappa[0] + 1. / 6 * eta[0] ** 3 * kappa[1]
+ 1. / 2 * eta[0] * eta[2] * kappa[0]) * ca
tmp4 = (10. * eta[1] - 2. * eta[3] + 1. / 6 * eta[5]) * sb
tmp5 = - (2. * eta[1] ** 2 * kappa[2] - 1. / 6 * eta[1] ** 3 * kappa[3]
- 1. / 2 * eta[1] * eta[3] * kappa[2]) * cb
self.coeffs[1, 7] = tmp1 + tmp2 + tmp3 + tmp4 + tmp5
self.s_dot = lambda u: max(np.linalg.norm(
self.coeffs[:, 1:].dot(np.array(
[1, 2. * u, 3. * u**2, 4. * u**3,
5. * u**4, 6. * u**5, 7. * u**6]))), 1e-6)
self.f_length = lambda ue: quad(lambda u: self.s_dot(u), 0, ue)
self.segment_length = self.f_length(1)[0]
def calc_point(self, u):
"""
Eta3PathSegment::calc_point
input
u - parametric representation of a point along the segment, 0 <= u <= 1
returns
(x,y) of point along the segment
"""
assert(0 <= u <= 1)
return self.coeffs.dot(np.array([1, u, u**2, u**3, u**4, u**5, u**6, u**7]))
def calc_deriv(self, u, order=1):
"""
Eta3PathSegment::calc_deriv
input
u - parametric representation of a point along the segment, 0 <= u <= 1
returns
(d^nx/du^n,d^ny/du^n) of point along the segment, for 0 < n <= 2
"""
assert(0 <= u <= 1)
assert(0 < order <= 2)
if order == 1:
return self.coeffs[:, 1:].dot(np.array([1, 2. * u, 3. * u**2, 4. * u**3, 5. * u**4, 6. * u**5, 7. * u**6]))
return self.coeffs[:, 2:].dot(np.array([2, 6. * u, 12. * u**2, 20. * u**3, 30. * u**4, 42. * u**5]))
def test1():
for i in range(10):
path_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 3.0, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
eta = [i, i, 0, 0, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
path = Eta3Path(path_segments)
# interpolate at several points along the path
ui = np.linspace(0, len(path_segments), 1001)
pos = np.empty((2, ui.size))
for j, u in enumerate(ui):
pos[:, j] = path.calc_path_point(u)
if show_animation:
# plot the path
plt.plot(pos[0, :], pos[1, :])
# 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.pause(1.0)
if show_animation:
plt.close("all")
def test2():
for i in range(10):
path_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 3.0, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
eta = [0, 0, (i - 5) * 20, (5 - i) * 20, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
path = Eta3Path(path_segments)
# interpolate at several points along the path
ui = np.linspace(0, len(path_segments), 1001)
pos = np.empty((2, ui.size))
for j, u in enumerate(ui):
pos[:, j] = path.calc_path_point(u)
if show_animation:
# plot the path
plt.plot(pos[0, :], pos[1, :])
plt.pause(1.0)
if show_animation:
plt.close("all")
def test3():
path_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 1.5, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
eta = [4.27, 4.27, 0, 0, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 2: line segment
start_pose = [4, 1.5, 0]
end_pose = [5.5, 1.5, 0]
kappa = [0, 0, 0, 0]
eta = [0, 0, 0, 0, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 3: cubic spiral
start_pose = [5.5, 1.5, 0]
end_pose = [7.4377, 1.8235, 0.6667]
kappa = [0, 0, 1, 1]
eta = [1.88, 1.88, 0, 0, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 4: generic twirl arc
start_pose = [7.4377, 1.8235, 0.6667]
end_pose = [7.8, 4.3, 1.8]
kappa = [1, 1, 0.5, 0]
eta = [7, 10, 10, -10, 4, 4]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 5: circular arc
start_pose = [7.8, 4.3, 1.8]
end_pose = [5.4581, 5.8064, 3.3416]
kappa = [0.5, 0, 0.5, 0]
eta = [2.98, 2.98, 0, 0, 0, 0]
path_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# construct the whole path
path = Eta3Path(path_segments)
# interpolate at several points along the path
ui = np.linspace(0, len(path_segments), 1001)
pos = np.empty((2, ui.size))
for i, u in enumerate(ui):
pos[:, i] = path.calc_path_point(u)
# plot the path
if show_animation:
plt.figure('Path from Reference')
plt.plot(pos[0, :], pos[1, :])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Path')
plt.pause(1.0)
plt.show()
def main():
"""
recreate path from reference (see Table 1)
"""
test1()
test2()
test3()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/Eta3SplinePath/eta3_spline_path.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 4,940 |
```python
"""
Informed RRT* path planning
author: Karan Chawla
Atsushi Sakai(@Atsushi_twi)
Reference: Informed RRT*: Optimal Sampling-based Path planning Focused via
Direct Sampling of an Admissible Ellipsoidal Heuristic
path_to_url
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import copy
import math
import random
import matplotlib.pyplot as plt
import numpy as np
from utils.angle import rot_mat_2d
show_animation = True
class InformedRRTStar:
def __init__(self, start, goal, obstacle_list, rand_area, expand_dis=0.5,
goal_sample_rate=10, max_iter=200):
self.start = Node(start[0], start[1])
self.goal = Node(goal[0], goal[1])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.expand_dis = expand_dis
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.node_list = None
def informed_rrt_star_search(self, animation=True):
self.node_list = [self.start]
# max length we expect to find in our 'informed' sample space,
# starts as infinite
c_best = float('inf')
solution_set = set()
path = None
# Computing the sampling space
c_min = math.hypot(self.start.x - self.goal.x,
self.start.y - self.goal.y)
x_center = np.array([[(self.start.x + self.goal.x) / 2.0],
[(self.start.y + self.goal.y) / 2.0], [0]])
a1 = np.array([[(self.goal.x - self.start.x) / c_min],
[(self.goal.y - self.start.y) / c_min], [0]])
e_theta = math.atan2(a1[1, 0], a1[0, 0])
# first column of identity matrix transposed
id1_t = np.array([1.0, 0.0, 0.0]).reshape(1, 3)
m = a1 @ id1_t
u, s, vh = np.linalg.svd(m, True, True)
c = u @ np.diag(
[1.0, 1.0,
np.linalg.det(u) * np.linalg.det(np.transpose(vh))]) @ vh
for i in range(self.max_iter):
# Sample space is defined by c_best
# c_min is the minimum distance between the start point and
# the goal x_center is the midpoint between the start and the
# goal c_best changes when a new path is found
rnd = self.informed_sample(c_best, c_min, x_center, c)
n_ind = self.get_nearest_list_index(self.node_list, rnd)
nearest_node = self.node_list[n_ind]
# steer
theta = math.atan2(rnd[1] - nearest_node.y,
rnd[0] - nearest_node.x)
new_node = self.get_new_node(theta, n_ind, nearest_node)
d = self.line_cost(nearest_node, new_node)
no_collision = self.check_collision(nearest_node, theta, d)
if no_collision:
near_inds = self.find_near_nodes(new_node)
new_node = self.choose_parent(new_node, near_inds)
self.node_list.append(new_node)
self.rewire(new_node, near_inds)
if self.is_near_goal(new_node):
if self.check_segment_collision(new_node.x, new_node.y,
self.goal.x, self.goal.y):
solution_set.add(new_node)
last_index = len(self.node_list) - 1
temp_path = self.get_final_course(last_index)
temp_path_len = self.get_path_len(temp_path)
if temp_path_len < c_best:
path = temp_path
c_best = temp_path_len
if animation:
self.draw_graph(x_center=x_center, c_best=c_best, c_min=c_min,
e_theta=e_theta, rnd=rnd)
return path
def choose_parent(self, new_node, near_inds):
if len(near_inds) == 0:
return new_node
d_list = []
for i in near_inds:
dx = new_node.x - self.node_list[i].x
dy = new_node.y - self.node_list[i].y
d = math.hypot(dx, dy)
theta = math.atan2(dy, dx)
if self.check_collision(self.node_list[i], theta, d):
d_list.append(self.node_list[i].cost + d)
else:
d_list.append(float('inf'))
min_cost = min(d_list)
min_ind = near_inds[d_list.index(min_cost)]
if min_cost == float('inf'):
print("min cost is inf")
return new_node
new_node.cost = min_cost
new_node.parent = min_ind
return new_node
def find_near_nodes(self, new_node):
n_node = len(self.node_list)
r = 50.0 * math.sqrt(math.log(n_node) / n_node)
d_list = [(node.x - new_node.x) ** 2 + (node.y - new_node.y) ** 2 for
node in self.node_list]
near_inds = [d_list.index(i) for i in d_list if i <= r ** 2]
return near_inds
def informed_sample(self, c_max, c_min, x_center, c):
if c_max < float('inf'):
r = [c_max / 2.0, math.sqrt(c_max ** 2 - c_min ** 2) / 2.0,
math.sqrt(c_max ** 2 - c_min ** 2) / 2.0]
rl = np.diag(r)
x_ball = self.sample_unit_ball()
rnd = np.dot(np.dot(c, rl), x_ball) + x_center
rnd = [rnd[(0, 0)], rnd[(1, 0)]]
else:
rnd = self.sample_free_space()
return rnd
@staticmethod
def sample_unit_ball():
a = random.random()
b = random.random()
if b < a:
a, b = b, a
sample = (b * math.cos(2 * math.pi * a / b),
b * math.sin(2 * math.pi * a / b))
return np.array([[sample[0]], [sample[1]], [0]])
def sample_free_space(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = [random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand)]
else:
rnd = [self.goal.x, self.goal.y]
return rnd
@staticmethod
def get_path_len(path):
path_len = 0
for i in range(1, len(path)):
node1_x = path[i][0]
node1_y = path[i][1]
node2_x = path[i - 1][0]
node2_y = path[i - 1][1]
path_len += math.hypot(node1_x - node2_x, node1_y - node2_y)
return path_len
@staticmethod
def line_cost(node1, node2):
return math.hypot(node1.x - node2.x, node1.y - node2.y)
@staticmethod
def get_nearest_list_index(nodes, rnd):
d_list = [(node.x - rnd[0]) ** 2 + (node.y - rnd[1]) ** 2 for node in
nodes]
min_index = d_list.index(min(d_list))
return min_index
def get_new_node(self, theta, n_ind, nearest_node):
new_node = copy.deepcopy(nearest_node)
new_node.x += self.expand_dis * math.cos(theta)
new_node.y += self.expand_dis * math.sin(theta)
new_node.cost += self.expand_dis
new_node.parent = n_ind
return new_node
def is_near_goal(self, node):
d = self.line_cost(node, self.goal)
if d < self.expand_dis:
return True
return False
def rewire(self, new_node, near_inds):
n_node = len(self.node_list)
for i in near_inds:
near_node = self.node_list[i]
d = math.hypot(near_node.x - new_node.x, near_node.y - new_node.y)
s_cost = new_node.cost + d
if near_node.cost > s_cost:
theta = math.atan2(new_node.y - near_node.y,
new_node.x - near_node.x)
if self.check_collision(near_node, theta, d):
near_node.parent = n_node - 1
near_node.cost = s_cost
@staticmethod
def distance_squared_point_to_segment(v, w, p):
# Return minimum distance between line segment vw and point p
if np.array_equal(v, w):
return (p - v).dot(p - v) # v == w case
l2 = (w - v).dot(w - v) # i.e. |w-v|^2 - avoid a sqrt
# Consider the line extending the segment,
# parameterized as v + t (w - v).
# We find projection of point p onto the line.
# It falls where t = [(p-v) . (w-v)] / |w-v|^2
# We clamp t from [0,1] to handle points outside the segment vw.
t = max(0, min(1, (p - v).dot(w - v) / l2))
projection = v + t * (w - v) # Projection falls on the segment
return (p - projection).dot(p - projection)
def check_segment_collision(self, x1, y1, x2, y2):
for (ox, oy, size) in self.obstacle_list:
dd = self.distance_squared_point_to_segment(
np.array([x1, y1]), np.array([x2, y2]), np.array([ox, oy]))
if dd <= size ** 2:
return False # collision
return True
def check_collision(self, near_node, theta, d):
tmp_node = copy.deepcopy(near_node)
end_x = tmp_node.x + math.cos(theta) * d
end_y = tmp_node.y + math.sin(theta) * d
return self.check_segment_collision(tmp_node.x, tmp_node.y,
end_x, end_y)
def get_final_course(self, last_index):
path = [[self.goal.x, self.goal.y]]
while self.node_list[last_index].parent is not None:
node = self.node_list[last_index]
path.append([node.x, node.y])
last_index = node.parent
path.append([self.start.x, self.start.y])
return path
def draw_graph(self, x_center=None, c_best=None, c_min=None, e_theta=None,
rnd=None):
plt.clf()
# 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 rnd is not None:
plt.plot(rnd[0], rnd[1], "^k")
if c_best != float('inf'):
self.plot_ellipse(x_center, c_best, c_min, e_theta)
for node in self.node_list:
if node.parent is not None:
if node.x or node.y is not None:
plt.plot([node.x, self.node_list[node.parent].x],
[node.y, self.node_list[node.parent].y], "-g")
for (ox, oy, size) in self.obstacle_list:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.goal.x, self.goal.y, "xr")
plt.axis([self.min_rand, self.max_rand, self.min_rand, self.max_rand])
plt.grid(True)
plt.pause(0.01)
@staticmethod
def plot_ellipse(x_center, c_best, c_min, e_theta): # pragma: no cover
a = math.sqrt(c_best ** 2 - c_min ** 2) / 2.0
b = c_best / 2.0
angle = math.pi / 2.0 - e_theta
cx = x_center[0]
cy = x_center[1]
t = np.arange(0, 2 * math.pi + 0.1, 0.1)
x = [a * math.cos(it) for it in t]
y = [b * math.sin(it) for it in t]
fx = rot_mat_2d(-angle) @ np.array([x, y])
px = np.array(fx[0, :] + cx).flatten()
py = np.array(fx[1, :] + cy).flatten()
plt.plot(cx, cy, "xc")
plt.plot(px, py, "--c")
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.cost = 0.0
self.parent = None
def main():
print("Start informed rrt star planning")
# create obstacles
obstacle_list = [(5, 5, 0.5), (9, 6, 1), (7, 5, 1), (1, 5, 1), (3, 6, 1),
(7, 9, 1)]
# Set params
rrt = InformedRRTStar(start=[0, 0], goal=[5, 10], rand_area=[-2, 15],
obstacle_list=obstacle_list)
path = rrt.informed_rrt_star_search(animation=show_animation)
print("Done!!")
# Plot path
if show_animation:
rrt.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/InformedRRTStar/informed_rrt_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,166 |
```python
"""
Distance/Path Transform Wavefront Coverage Path Planner
author: Todd Tang
paper: Planning paths of complete coverage of an unstructured environment
by a mobile robot - Zelinsky et.al.
link: path_to_url
"""
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
do_animation = True
def transform(
grid_map, src, distance_type='chessboard',
transform_type='path', alpha=0.01
):
"""transform
calculating transform of transform_type from src
in given distance_type
:param grid_map: 2d binary map
:param src: distance transform source
:param distance_type: type of distance used
:param transform_type: type of transform used
:param alpha: weight of Obstacle Transform used when using path_transform
"""
n_rows, n_cols = grid_map.shape
if n_rows == 0 or n_cols == 0:
sys.exit('Empty grid_map.')
inc_order = [[0, 1], [1, 1], [1, 0], [1, -1],
[0, -1], [-1, -1], [-1, 0], [-1, 1]]
if distance_type == 'chessboard':
cost = [1, 1, 1, 1, 1, 1, 1, 1]
elif distance_type == 'eculidean':
cost = [1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2), 1, np.sqrt(2)]
else:
sys.exit('Unsupported distance type.')
transform_matrix = float('inf') * np.ones_like(grid_map, dtype=float)
transform_matrix[src[0], src[1]] = 0
if transform_type == 'distance':
eT = np.zeros_like(grid_map)
elif transform_type == 'path':
eT = ndimage.distance_transform_cdt(1 - grid_map, distance_type)
else:
sys.exit('Unsupported transform type.')
# set obstacle transform_matrix value to infinity
for i in range(n_rows):
for j in range(n_cols):
if grid_map[i][j] == 1.0:
transform_matrix[i][j] = float('inf')
is_visited = np.zeros_like(transform_matrix, dtype=bool)
is_visited[src[0], src[1]] = True
traversal_queue = [src]
calculated = [(src[0] - 1) * n_cols + src[1]]
def is_valid_neighbor(g_i, g_j):
return 0 <= g_i < n_rows and 0 <= g_j < n_cols \
and not grid_map[g_i][g_j]
while traversal_queue:
i, j = traversal_queue.pop(0)
for k, inc in enumerate(inc_order):
ni = i + inc[0]
nj = j + inc[1]
if is_valid_neighbor(ni, nj):
is_visited[i][j] = True
# update transform_matrix
transform_matrix[i][j] = min(
transform_matrix[i][j],
transform_matrix[ni][nj] + cost[k] + alpha * eT[ni][nj])
if not is_visited[ni][nj] \
and ((ni - 1) * n_cols + nj) not in calculated:
traversal_queue.append((ni, nj))
calculated.append((ni - 1) * n_cols + nj)
return transform_matrix
def get_search_order_increment(start, goal):
if start[0] >= goal[0] and start[1] >= goal[1]:
order = [[1, 0], [0, 1], [-1, 0], [0, -1],
[1, 1], [1, -1], [-1, 1], [-1, -1]]
elif start[0] <= goal[0] and start[1] >= goal[1]:
order = [[-1, 0], [0, 1], [1, 0], [0, -1],
[-1, 1], [-1, -1], [1, 1], [1, -1]]
elif start[0] >= goal[0] and start[1] <= goal[1]:
order = [[1, 0], [0, -1], [-1, 0], [0, 1],
[1, -1], [-1, -1], [1, 1], [-1, 1]]
elif start[0] <= goal[0] and start[1] <= goal[1]:
order = [[-1, 0], [0, -1], [0, 1], [1, 0],
[-1, -1], [-1, 1], [1, -1], [1, 1]]
else:
sys.exit('get_search_order_increment: cannot determine \
start=>goal increment order')
return order
def wavefront(transform_matrix, start, goal):
"""wavefront
performing wavefront coverage path planning
:param transform_matrix: the transform matrix
:param start: start point of planning
:param goal: goal point of planning
"""
path = []
n_rows, n_cols = transform_matrix.shape
def is_valid_neighbor(g_i, g_j):
is_i_valid_bounded = 0 <= g_i < n_rows
is_j_valid_bounded = 0 <= g_j < n_cols
if is_i_valid_bounded and is_j_valid_bounded:
return not is_visited[g_i][g_j] and \
transform_matrix[g_i][g_j] != float('inf')
return False
inc_order = get_search_order_increment(start, goal)
current_node = start
is_visited = np.zeros_like(transform_matrix, dtype=bool)
while current_node != goal:
i, j = current_node
path.append((i, j))
is_visited[i][j] = True
max_T = float('-inf')
i_max = (-1, -1)
i_last = 0
for i_last in range(len(path)):
current_node = path[-1 - i_last] # get latest node in path
for ci, cj in inc_order:
ni, nj = current_node[0] + ci, current_node[1] + cj
if is_valid_neighbor(ni, nj) and \
transform_matrix[ni][nj] > max_T:
i_max = (ni, nj)
max_T = transform_matrix[ni][nj]
if i_max != (-1, -1):
break
if i_max == (-1, -1):
break
else:
current_node = i_max
if i_last != 0:
print('backtracing to', current_node)
path.append(goal)
return path
def visualize_path(grid_map, start, goal, path): # pragma: no cover
oy, ox = start
gy, gx = goal
px, py = np.transpose(np.flipud(np.fliplr(path)))
if not do_animation:
plt.imshow(grid_map, cmap='Greys')
plt.plot(ox, oy, "-xy")
plt.plot(px, py, "-r")
plt.plot(gx, gy, "-pg")
plt.show()
else:
for ipx, ipy in zip(px, py):
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.imshow(grid_map, cmap='Greys')
plt.plot(ox, oy, "-xb")
plt.plot(px, py, "-r")
plt.plot(gx, gy, "-pg")
plt.plot(ipx, ipy, "or")
plt.axis("equal")
plt.grid(True)
plt.pause(0.1)
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
img = plt.imread(os.path.join(dir_path, 'map', 'test.png'))
img = 1 - img # revert pixel values
start = (43, 0)
goal = (0, 0)
# distance transform wavefront
DT = transform(img, goal, transform_type='distance')
DT_path = wavefront(DT, start, goal)
visualize_path(img, start, goal, DT_path)
# path transform wavefront
PT = transform(img, goal, transform_type='path', alpha=0.01)
PT_path = wavefront(PT, start, goal)
visualize_path(img, start, goal, PT_path)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/PathPlanning/WavefrontCPP/wavefront_coverage_path_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,929 |
```python
"""
Greedy Best-First grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class BestFirstSearchPlanner:
def __init__(self, ox, oy, reso, rr):
"""
Initialize grid map for greedy best-first planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.reso = reso
self.rr = rr
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, pind, parent):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.pind = pind
self.parent = parent
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.pind)
def planning(self, sx, sy, gx, gy):
"""
Greedy Best-First search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
nstart = self.Node(self.calc_xyindex(sx, self.minx),
self.calc_xyindex(sy, self.miny), 0.0, -1, None)
ngoal = self.Node(self.calc_xyindex(gx, self.minx),
self.calc_xyindex(gy, self.miny), 0.0, -1, None)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(nstart)] = nstart
while True:
if len(open_set) == 0:
print("Open set is empty..")
break
c_id = min(
open_set,
key=lambda o: self.calc_heuristic(ngoal, open_set[o]))
current = open_set[c_id]
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current.x, self.minx),
self.calc_grid_position(current.y, self.miny), "xc")
# 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 len(closed_set.keys()) % 10 == 0:
plt.pause(0.001)
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
if current.x == ngoal.x and current.y == ngoal.y:
print("Found goal")
ngoal.pind = current.pind
ngoal.cost = current.cost
break
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2],
c_id, current)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if n_id in closed_set:
continue
if n_id not in open_set:
open_set[n_id] = node
else:
if open_set[n_id].cost > node.cost:
open_set[n_id] = node
closed_set[ngoal.pind] = current
rx, ry = self.calc_final_path(ngoal, closed_set)
return rx, ry
def calc_final_path(self, ngoal, closedset):
# generate final course
rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
self.calc_grid_position(ngoal.y, self.miny)]
n = closedset[ngoal.pind]
while n is not None:
rx.append(self.calc_grid_position(n.x, self.minx))
ry.append(self.calc_grid_position(n.y, self.miny))
n = n.parent
return rx, ry
@staticmethod
def calc_heuristic(n1, n2):
w = 1.0 # weight of heuristic
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
return d
def calc_grid_position(self, index, minp):
"""
calc grid position
:param index:
:param minp:
:return:
"""
pos = index * self.reso + minp
return pos
def calc_xyindex(self, position, min_pos):
return round((position - min_pos) / self.reso)
def calc_grid_index(self, node):
return (node.y - self.miny) * self.xwidth + (node.x - self.minx)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.minx)
py = self.calc_grid_position(node.y, self.miny)
if px < self.minx:
return False
elif py < self.miny:
return False
elif px >= self.maxx:
return False
elif py >= self.maxy:
return False
# collision check
if self.obmap[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.minx = round(min(ox))
self.miny = round(min(oy))
self.maxx = round(max(ox))
self.maxy = round(max(oy))
print("min_x:", self.minx)
print("min_y:", self.miny)
print("max_x:", self.maxx)
print("max_y:", self.maxy)
self.xwidth = round((self.maxx - self.minx) / self.reso)
self.ywidth = round((self.maxy - self.miny) / self.reso)
print("x_width:", self.xwidth)
print("y_width:", self.ywidth)
# obstacle map generation
self.obmap = [[False for _ in range(self.ywidth)]
for _ in range(self.xwidth)]
for ix in range(self.xwidth):
x = self.calc_grid_position(ix, self.minx)
for iy in range(self.ywidth):
y = self.calc_grid_position(iy, self.miny)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obmap[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
greedybestfirst = BestFirstSearchPlanner(ox, oy, grid_size, robot_radius)
rx, ry = greedybestfirst.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/GreedyBestFirstSearch/greedy_best_first_search.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,063 |
```python
"""
flowfield pathfinding
author: Sarim Mehdi (muhammadsarim.mehdi@studio.unibo.it)
Source: path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
show_animation = True
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
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
class FlowField:
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 = {}
def find_path(self):
self.create_cost_field()
self.create_integration_field()
self.assign_vectors()
self.follow_vectors()
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
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]
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
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()
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()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/FlowField/flowfield.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,532 |
```python
"""
Path planning Sample Code with RRT with Dubins path
author: AtsushiSakai(@Atsushi_twi)
"""
import copy
import math
import random
import numpy as np
import matplotlib.pyplot as plt
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent)) # root dir
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from RRT.rrt import RRT
from DubinsPath import dubins_path_planner
from utils.plot import plot_arrow
show_animation = True
class RRTDubins(RRT):
"""
Class for RRT planning with Dubins path
"""
class Node(RRT.Node):
"""
RRT Node
"""
def __init__(self, x, y, yaw):
super().__init__(x, y)
self.cost = 0
self.yaw = yaw
self.path_yaw = []
def __init__(self, start, goal, obstacle_list, rand_area,
goal_sample_rate=10,
max_iter=200,
robot_radius=0.0
):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1], start[2])
self.end = self.Node(goal[0], goal[1], goal[2])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.curvature = 1.0 # for dubins path
self.goal_yaw_th = np.deg2rad(1.0)
self.goal_xy_th = 0.5
self.robot_radius = robot_radius
def planning(self, animation=True, search_until_max_iter=True):
"""
execute planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind], rnd)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
self.node_list.append(new_node)
if animation and i % 5 == 0:
self.plot_start_goal_arrow()
self.draw_graph(rnd)
if (not search_until_max_iter) and new_node: # check reaching the goal
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
else:
print("Cannot find path")
return None
def draw_graph(self, rnd=None): # pragma: no cover
plt.clf()
# 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 rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
self.plot_start_goal_arrow()
plt.pause(0.01)
def plot_start_goal_arrow(self): # pragma: no cover
plot_arrow(self.start.x, self.start.y, self.start.yaw)
plot_arrow(self.end.x, self.end.y, self.end.yaw)
def steer(self, from_node, to_node):
px, py, pyaw, mode, course_lengths = \
dubins_path_planner.plan_dubins_path(
from_node.x, from_node.y, from_node.yaw,
to_node.x, to_node.y, to_node.yaw, self.curvature)
if len(px) <= 1: # cannot find a dubins path
return None
new_node = copy.deepcopy(from_node)
new_node.x = px[-1]
new_node.y = py[-1]
new_node.yaw = pyaw[-1]
new_node.path_x = px
new_node.path_y = py
new_node.path_yaw = pyaw
new_node.cost += sum([abs(c) for c in course_lengths])
new_node.parent = from_node
return new_node
def calc_new_cost(self, from_node, to_node):
_, _, _, _, course_length = dubins_path_planner.plan_dubins_path(
from_node.x, from_node.y, from_node.yaw,
to_node.x, to_node.y, to_node.yaw, self.curvature)
return from_node.cost + course_length
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand),
random.uniform(-math.pi, math.pi)
)
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y, self.end.yaw)
return rnd
def search_best_goal_node(self):
goal_indexes = []
for (i, node) in enumerate(self.node_list):
if self.calc_dist_to_goal(node.x, node.y) <= self.goal_xy_th:
goal_indexes.append(i)
# angle check
final_goal_indexes = []
for i in goal_indexes:
if abs(self.node_list[i].yaw - self.end.yaw) <= self.goal_yaw_th:
final_goal_indexes.append(i)
if not final_goal_indexes:
return None
min_cost = min([self.node_list[i].cost for i in final_goal_indexes])
for i in final_goal_indexes:
if self.node_list[i].cost == min_cost:
return i
return None
def generate_final_course(self, goal_index):
print("final")
path = [[self.end.x, self.end.y]]
node = self.node_list[goal_index]
while node.parent:
for (ix, iy) in zip(reversed(node.path_x), reversed(node.path_y)):
path.append([ix, iy])
node = node.parent
path.append([self.start.x, self.start.y])
return path
def main():
print("Start " + __file__)
# ====Search Path with RRT====
obstacleList = [
(5, 5, 1),
(3, 6, 2),
(3, 8, 2),
(3, 10, 2),
(7, 5, 2),
(9, 5, 2)
] # [x,y,size(radius)]
# Set Initial parameters
start = [0.0, 0.0, np.deg2rad(0.0)]
goal = [10.0, 10.0, np.deg2rad(0.0)]
rrt_dubins = RRTDubins(start, goal, obstacleList, [-2.0, 15.0])
path = rrt_dubins.planning(animation=show_animation)
# Draw final path
if show_animation: # pragma: no cover
rrt_dubins.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRTDubins/rrt_dubins.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,808 |
```python
"""
eta^3 polynomials trajectory planner
author: Joe Dinius, Ph.D (path_to_url
Atsushi Sakai (@Atsushi_twi)
Refs:
- path_to_url
- [eta^3-Splines for the Smooth Path Generation of Wheeled Mobile Robots]
(path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from Eta3SplinePath.eta3_spline_path import Eta3Path, Eta3PathSegment
show_animation = True
class MaxVelocityNotReached(Exception):
def __init__(self, actual_vel, max_vel):
self.message = 'Actual velocity {} does not equal desired max velocity {}!'.format(
actual_vel, max_vel)
class eta3_trajectory(Eta3Path):
"""
eta3_trajectory
input
segments: list of `eta3_trajectory_segment` instances defining a continuous trajectory
"""
def __init__(self, segments, max_vel, v0=0.0, a0=0.0, max_accel=2.0, max_jerk=5.0):
# ensure that all inputs obey the assumptions of the model
assert max_vel > 0 and v0 >= 0 and a0 >= 0 and max_accel > 0 and max_jerk > 0 \
and a0 <= max_accel and v0 <= max_vel
super(eta3_trajectory, self).__init__(segments=segments)
self.total_length = sum([s.segment_length for s in self.segments])
self.max_vel = float(max_vel)
self.v0 = float(v0)
self.a0 = float(a0)
self.max_accel = float(max_accel)
self.max_jerk = float(max_jerk)
length_array = np.array([s.segment_length for s in self.segments])
# add a zero to the beginning for finding the correct segment_id
self.cum_lengths = np.concatenate(
(np.array([0]), np.cumsum(length_array)))
# compute velocity profile on top of the path
self.velocity_profile()
self.ui_prev = 0
self.prev_seg_id = 0
def velocity_profile(self):
r""" /~~~~~----------------\
/ \
/ \
/ \
/ \
(v=v0, a=a0) ~~~~~ \
\
\ ~~~~~ (vf=0, af=0)
pos.|pos.|neg.| cruise at |neg.| neg. |neg.
max |max.|max.| max. |max.| max. |max.
jerk|acc.|jerk| velocity |jerk| acc. |jerk
index 0 1 2 3 (optional) 4 5 6
"""
# delta_a: accel change from initial position to end of maximal jerk section
delta_a = self.max_accel - self.a0
# t_s1: time of traversal of maximal jerk section
t_s1 = delta_a / self.max_jerk
# v_s1: velocity at the end of the maximal jerk section
v_s1 = self.v0 + self.a0 * t_s1 + self.max_jerk * t_s1**2 / 2.
# s_s1: length of the maximal jerk section
s_s1 = self.v0 * t_s1 + self.a0 * t_s1**2 / 2. + self.max_jerk * t_s1**3 / 6.
# t_sf: time of traversal of final section, which is also maximal jerk, but has final velocity 0
t_sf = self.max_accel / self.max_jerk
# v_sf: velocity at beginning of final section
v_sf = self.max_jerk * t_sf**2 / 2.
# s_sf: length of final section
s_sf = self.max_jerk * t_sf**3 / 6.
# solve for the maximum achievable velocity based on the kinematic limits imposed by max_accel and max_jerk
# this leads to a quadratic equation in v_max: a*v_max**2 + b*v_max + c = 0
a = 1 / self.max_accel
b = 3. * self.max_accel / (2. * self.max_jerk) + v_s1 / self.max_accel - (
self.max_accel**2 / self.max_jerk + v_s1) / self.max_accel
c = s_s1 + s_sf - self.total_length - 7. * self.max_accel**3 / (3. * self.max_jerk**2) \
- v_s1 * (self.max_accel / self.max_jerk + v_s1 / self.max_accel) \
+ (self.max_accel**2 / self.max_jerk + v_s1 /
self.max_accel)**2 / (2. * self.max_accel)
v_max = (-b + np.sqrt(b**2 - 4. * a * c)) / (2. * a)
# v_max represents the maximum velocity that could be attained if there was no cruise period
# (i.e. driving at constant speed without accelerating or jerking)
# if this velocity is less than our desired max velocity, the max velocity needs to be updated
if self.max_vel > v_max:
# when this condition is tripped, there will be no cruise period (s_cruise=0)
self.max_vel = v_max
# setup arrays to store values at END of trajectory sections
self.times = np.zeros((7,))
self.vels = np.zeros((7,))
self.seg_lengths = np.zeros((7,))
# Section 0: max jerk up to max acceleration
self.times[0] = t_s1
self.vels[0] = v_s1
self.seg_lengths[0] = s_s1
# Section 1: accelerate at max_accel
index = 1
# compute change in velocity over the section
delta_v = (self.max_vel - self.max_jerk * (self.max_accel /
self.max_jerk)**2 / 2.) - self.vels[index - 1]
self.times[index] = delta_v / self.max_accel
self.vels[index] = self.vels[index - 1] + \
self.max_accel * self.times[index]
self.seg_lengths[index] = self.vels[index - 1] * \
self.times[index] + self.max_accel * self.times[index]**2 / 2.
# Section 2: decrease acceleration (down to 0) until max speed is hit
index = 2
self.times[index] = self.max_accel / self.max_jerk
self.vels[index] = self.vels[index - 1] + self.max_accel * self.times[index] \
- self.max_jerk * self.times[index]**2 / 2.
# as a check, the velocity at the end of the section should be self.max_vel
if not np.isclose(self.vels[index], self.max_vel):
raise MaxVelocityNotReached(self.vels[index], self.max_vel)
self.seg_lengths[index] = self.vels[index - 1] * self.times[index] + self.max_accel * self.times[index]**2 / 2. \
- self.max_jerk * self.times[index]**3 / 6.
# Section 3: will be done last
# Section 4: apply min jerk until min acceleration is hit
index = 4
self.times[index] = self.max_accel / self.max_jerk
self.vels[index] = self.max_vel - \
self.max_jerk * self.times[index]**2 / 2.
self.seg_lengths[index] = self.max_vel * self.times[index] - \
self.max_jerk * self.times[index]**3 / 6.
# Section 5: continue deceleration at max rate
index = 5
# compute velocity change over sections
delta_v = self.vels[index - 1] - v_sf
self.times[index] = delta_v / self.max_accel
self.vels[index] = self.vels[index - 1] - \
self.max_accel * self.times[index]
self.seg_lengths[index] = self.vels[index - 1] * \
self.times[index] - self.max_accel * self.times[index]**2 / 2.
# Section 6(final): max jerk to get to zero velocity and zero acceleration simultaneously
index = 6
self.times[index] = t_sf
self.vels[index] = self.vels[index - 1] - self.max_jerk * t_sf**2 / 2.
try:
assert np.isclose(self.vels[index], 0)
except AssertionError as e:
print('The final velocity {} is not zero'.format(self.vels[index]))
raise e
self.seg_lengths[index] = s_sf
if self.seg_lengths.sum() < self.total_length:
index = 3
# the length of the cruise section is whatever length hasn't already been accounted for
# NOTE: the total array self.seg_lengths is summed because the entry for the cruise segment is
# initialized to 0!
self.seg_lengths[index] = self.total_length - \
self.seg_lengths.sum()
self.vels[index] = self.max_vel
self.times[index] = self.seg_lengths[index] / self.max_vel
# make sure that all of the times are positive, otherwise the kinematic limits
# chosen cannot be enforced on the path
assert(np.all(self.times >= 0))
self.total_time = self.times.sum()
def get_interp_param(self, seg_id, s, ui, tol=0.001):
def f(u):
return self.segments[seg_id].f_length(u)[0] - s
def fprime(u):
return self.segments[seg_id].s_dot(u)
while (0 <= ui <= 1) and abs(f(ui)) > tol:
ui -= f(ui) / fprime(ui)
ui = max(0, min(ui, 1))
return ui
def calc_traj_point(self, time):
# compute velocity at time
if time <= self.times[0]:
linear_velocity = self.v0 + self.max_jerk * time**2 / 2.
s = self.v0 * time + self.max_jerk * time**3 / 6
linear_accel = self.max_jerk * time
elif time <= self.times[:2].sum():
delta_t = time - self.times[0]
linear_velocity = self.vels[0] + self.max_accel * delta_t
s = self.seg_lengths[0] + self.vels[0] * \
delta_t + self.max_accel * delta_t**2 / 2.
linear_accel = self.max_accel
elif time <= self.times[:3].sum():
delta_t = time - self.times[:2].sum()
linear_velocity = self.vels[1] + self.max_accel * \
delta_t - self.max_jerk * delta_t**2 / 2.
s = self.seg_lengths[:2].sum() + self.vels[1] * delta_t + self.max_accel * delta_t**2 / 2. \
- self.max_jerk * delta_t**3 / 6.
linear_accel = self.max_accel - self.max_jerk * delta_t
elif time <= self.times[:4].sum():
delta_t = time - self.times[:3].sum()
linear_velocity = self.vels[3]
s = self.seg_lengths[:3].sum() + self.vels[3] * delta_t
linear_accel = 0.
elif time <= self.times[:5].sum():
delta_t = time - self.times[:4].sum()
linear_velocity = self.vels[3] - self.max_jerk * delta_t**2 / 2.
s = self.seg_lengths[:4].sum() + self.vels[3] * \
delta_t - self.max_jerk * delta_t**3 / 6.
linear_accel = -self.max_jerk * delta_t
elif time <= self.times[:-1].sum():
delta_t = time - self.times[:5].sum()
linear_velocity = self.vels[4] - self.max_accel * delta_t
s = self.seg_lengths[:5].sum() + self.vels[4] * \
delta_t - self.max_accel * delta_t**2 / 2.
linear_accel = -self.max_accel
elif time < self.times.sum():
delta_t = time - self.times[:-1].sum()
linear_velocity = self.vels[5] - self.max_accel * \
delta_t + self.max_jerk * delta_t**2 / 2.
s = self.seg_lengths[:-1].sum() + self.vels[5] * delta_t - self.max_accel * delta_t**2 / 2. \
+ self.max_jerk * delta_t**3 / 6.
linear_accel = -self.max_accel + self.max_jerk * delta_t
else:
linear_velocity = 0.
s = self.total_length
linear_accel = 0.
seg_id = np.max(np.argwhere(self.cum_lengths <= s))
# will happen at the end of the segment
if seg_id == len(self.segments):
seg_id -= 1
ui = 1
else:
# compute interpolation parameter using length from current segment's starting point
curr_segment_length = s - self.cum_lengths[seg_id]
ui = self.get_interp_param(
seg_id=seg_id, s=curr_segment_length, ui=self.ui_prev)
if not seg_id == self.prev_seg_id:
self.ui_prev = 0
else:
self.ui_prev = ui
self.prev_seg_id = seg_id
# compute angular velocity of current point= (ydd*xd - xdd*yd) / (xd**2 + yd**2)
d = self.segments[seg_id].calc_deriv(ui, order=1)
dd = self.segments[seg_id].calc_deriv(ui, order=2)
# su - the rate of change of arclength wrt u
su = self.segments[seg_id].s_dot(ui)
if not np.isclose(su, 0.) and not np.isclose(linear_velocity, 0.):
# ut - time-derivative of interpolation parameter u
ut = linear_velocity / su
# utt - time-derivative of ut
utt = linear_accel / su - \
(d[0] * dd[0] + d[1] * dd[1]) / su**2 * ut
xt = d[0] * ut
yt = d[1] * ut
xtt = dd[0] * ut**2 + d[0] * utt
ytt = dd[1] * ut**2 + d[1] * utt
angular_velocity = (ytt * xt - xtt * yt) / linear_velocity**2
else:
angular_velocity = 0.
# combine path point with orientation and velocities
pos = self.segments[seg_id].calc_point(ui)
state = np.array([pos[0], pos[1], np.arctan2(
d[1], d[0]), linear_velocity, angular_velocity])
return state
def test1(max_vel=0.5):
for i in range(10):
trajectory_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 3.0, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
eta = [i, i, 0, 0, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
traj = eta3_trajectory(trajectory_segments,
max_vel=max_vel, max_accel=0.5)
# interpolate at several points along the path
times = np.linspace(0, traj.total_time, 101)
state = np.empty((5, times.size))
for j, t in enumerate(times):
state[:, j] = traj.calc_traj_point(t)
if show_animation: # pragma: no cover
# plot the path
plt.plot(state[0, :], state[1, :])
plt.pause(1.0)
plt.show()
if show_animation:
plt.close("all")
def test2(max_vel=0.5):
for i in range(10):
trajectory_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 3.0, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
# NOTE: INTEGRATOR ERROR EXPLODES WHEN eta[:1] IS ZERO!
# was: eta = [0, 0, (i - 5) * 20, (5 - i) * 20, 0, 0], now is:
eta = [0.1, 0.1, (i - 5) * 20, (5 - i) * 20, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
traj = eta3_trajectory(trajectory_segments,
max_vel=max_vel, max_accel=0.5)
# interpolate at several points along the path
times = np.linspace(0, traj.total_time, 101)
state = np.empty((5, times.size))
for j, t in enumerate(times):
state[:, j] = traj.calc_traj_point(t)
if show_animation:
# plot the path
plt.plot(state[0, :], state[1, :])
plt.pause(1.0)
plt.show()
if show_animation:
plt.close("all")
def test3(max_vel=2.0):
trajectory_segments = []
# segment 1: lane-change curve
start_pose = [0, 0, 0]
end_pose = [4, 1.5, 0]
# NOTE: The ordering on kappa is [kappa_A, kappad_A, kappa_B, kappad_B], with kappad_* being the curvature derivative
kappa = [0, 0, 0, 0]
eta = [4.27, 4.27, 0, 0, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 2: line segment
start_pose = [4, 1.5, 0]
end_pose = [5.5, 1.5, 0]
kappa = [0, 0, 0, 0]
# NOTE: INTEGRATOR ERROR EXPLODES WHEN eta[:1] IS ZERO!
# was: eta = [0, 0, 0, 0, 0, 0], now is:
eta = [0.5, 0.5, 0, 0, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 3: cubic spiral
start_pose = [5.5, 1.5, 0]
end_pose = [7.4377, 1.8235, 0.6667]
kappa = [0, 0, 1, 1]
eta = [1.88, 1.88, 0, 0, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 4: generic twirl arc
start_pose = [7.4377, 1.8235, 0.6667]
end_pose = [7.8, 4.3, 1.8]
kappa = [1, 1, 0.5, 0]
eta = [7, 10, 10, -10, 4, 4]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# segment 5: circular arc
start_pose = [7.8, 4.3, 1.8]
end_pose = [5.4581, 5.8064, 3.3416]
kappa = [0.5, 0, 0.5, 0]
eta = [2.98, 2.98, 0, 0, 0, 0]
trajectory_segments.append(Eta3PathSegment(
start_pose=start_pose, end_pose=end_pose, eta=eta, kappa=kappa))
# construct the whole path
traj = eta3_trajectory(trajectory_segments,
max_vel=max_vel, max_accel=0.5, max_jerk=1)
# interpolate at several points along the path
times = np.linspace(0, traj.total_time, 1001)
state = np.empty((5, times.size))
for i, t in enumerate(times):
state[:, i] = traj.calc_traj_point(t)
# plot the path
if show_animation:
fig, ax = plt.subplots()
x, y = state[0, :], state[1, :]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segs = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segs, cmap=plt.get_cmap('inferno'))
ax.set_xlim(np.min(x) - 1, np.max(x) + 1)
ax.set_ylim(np.min(y) - 1, np.max(y) + 1)
lc.set_array(state[3, :])
lc.set_linewidth(3)
ax.add_collection(lc)
axcb = fig.colorbar(lc)
axcb.set_label('velocity(m/s)')
ax.set_title('Trajectory')
plt.xlabel('x')
plt.ylabel('y')
plt.pause(1.0)
fig1, ax1 = plt.subplots()
ax1.plot(times, state[3, :], 'b-')
ax1.set_xlabel('time(s)')
ax1.set_ylabel('velocity(m/s)', color='b')
ax1.tick_params('y', colors='b')
ax1.set_title('Control')
ax2 = ax1.twinx()
ax2.plot(times, state[4, :], 'r-')
ax2.set_ylabel('angular velocity(rad/s)', color='r')
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()
def main():
"""
recreate path from reference (see Table 1)
"""
# test1()
# test2()
test3()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/Eta3SplineTrajectory/eta3_spline_trajectory.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 5,217 |
```python
"""
Path planning code with LQR RRT*
author: AtsushiSakai(@Atsushi_twi)
"""
import copy
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from LQRPlanner.lqr_planner import LQRPlanner
from RRTStar.rrt_star import RRTStar
show_animation = True
class LQRRRTStar(RRTStar):
"""
Class for RRT star planning with LQR planning
"""
def __init__(self, start, goal, obstacle_list, rand_area,
goal_sample_rate=10,
max_iter=200,
connect_circle_dist=50.0,
step_size=0.2,
robot_radius=0.0,
):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1])
self.end = self.Node(goal[0], goal[1])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.connect_circle_dist = connect_circle_dist
self.curvature = 1.0
self.goal_xy_th = 0.5
self.step_size = step_size
self.robot_radius = robot_radius
self.lqr_planner = LQRPlanner()
def planning(self, animation=True, search_until_max_iter=True):
"""
RRT Star planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind], rnd)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
near_indexes = self.find_near_nodes(new_node)
new_node = self.choose_parent(new_node, near_indexes)
if new_node:
self.node_list.append(new_node)
self.rewire(new_node, near_indexes)
if animation and i % 5 == 0:
self.draw_graph(rnd)
if (not search_until_max_iter) and new_node: # check reaching the goal
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
else:
print("Cannot find path")
return None
def draw_graph(self, rnd=None):
plt.clf()
# 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 rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
plt.pause(0.01)
def search_best_goal_node(self):
dist_to_goal_list = [self.calc_dist_to_goal(n.x, n.y) for n in self.node_list]
goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.goal_xy_th]
if not goal_inds:
return None
min_cost = min([self.node_list[i].cost for i in goal_inds])
for i in goal_inds:
if self.node_list[i].cost == min_cost:
return i
return None
def calc_new_cost(self, from_node, to_node):
wx, wy = self.lqr_planner.lqr_planning(
from_node.x, from_node.y, to_node.x, to_node.y, show_animation=False)
px, py, course_lengths = self.sample_path(wx, wy, self.step_size)
if not course_lengths:
return float("inf")
return from_node.cost + sum(course_lengths)
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand)
)
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y)
return rnd
def generate_final_course(self, goal_index):
print("final")
path = [[self.end.x, self.end.y]]
node = self.node_list[goal_index]
while node.parent:
for (ix, iy) in zip(reversed(node.path_x), reversed(node.path_y)):
path.append([ix, iy])
node = node.parent
path.append([self.start.x, self.start.y])
return path
def sample_path(self, wx, wy, step):
px, py, clen = [], [], []
for i in range(len(wx) - 1):
for t in np.arange(0.0, 1.0, step):
px.append(t * wx[i + 1] + (1.0 - t) * wx[i])
py.append(t * wy[i + 1] + (1.0 - t) * wy[i])
dx = np.diff(px)
dy = np.diff(py)
clen = [math.hypot(idx, idy) for (idx, idy) in zip(dx, dy)]
return px, py, clen
def steer(self, from_node, to_node):
wx, wy = self.lqr_planner.lqr_planning(
from_node.x, from_node.y, to_node.x, to_node.y, show_animation=False)
px, py, course_lens = self.sample_path(wx, wy, self.step_size)
if px is None:
return None
newNode = copy.deepcopy(from_node)
newNode.x = px[-1]
newNode.y = py[-1]
newNode.path_x = px
newNode.path_y = py
newNode.cost += sum([abs(c) for c in course_lens])
newNode.parent = from_node
return newNode
def main(maxIter=200):
print("Start " + __file__)
# ====Search Path with RRT====
obstacleList = [
(5, 5, 1),
(4, 6, 1),
(4, 7.5, 1),
(4, 9, 1),
(6, 5, 1),
(7, 5, 1)
] # [x,y,size]
# Set Initial parameters
start = [0.0, 0.0]
goal = [6.0, 7.0]
lqr_rrt_star = LQRRRTStar(start, goal,
obstacleList,
[-2.0, 15.0])
path = lqr_rrt_star.planning(animation=show_animation)
# Draw final path
if show_animation: # pragma: no cover
lqr_rrt_star.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.001)
plt.show()
print("Done")
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/LQRRRTStar/lqr_rrt_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,782 |
```python
"""
LQR local path planning
author: Atsushi Sakai (@Atsushi_twi)
"""
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as la
SHOW_ANIMATION = True
class LQRPlanner:
def __init__(self):
self.MAX_TIME = 100.0 # Maximum simulation time
self.DT = 0.1 # Time tick
self.GOAL_DIST = 0.1
self.MAX_ITER = 150
self.EPS = 0.01
def lqr_planning(self, sx, sy, gx, gy, show_animation=True):
rx, ry = [sx], [sy]
x = np.array([sx - gx, sy - gy]).reshape(2, 1) # State vector
# Linear system model
A, B = self.get_system_model()
found_path = False
time = 0.0
while time <= self.MAX_TIME:
time += self.DT
u = self.lqr_control(A, B, x)
x = A @ x + B @ u
rx.append(x[0, 0] + gx)
ry.append(x[1, 0] + gy)
d = math.hypot(gx - rx[-1], gy - ry[-1])
if d <= self.GOAL_DIST:
found_path = True
break
# animation
if show_animation: # pragma: no cover
# 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(sx, sy, "or")
plt.plot(gx, gy, "ob")
plt.plot(rx, ry, "-r")
plt.axis("equal")
plt.pause(1.0)
if not found_path:
print("Cannot found path")
return [], []
return rx, ry
def solve_dare(self, A, B, Q, R):
"""
solve a discrete time_Algebraic Riccati equation (DARE)
"""
X, Xn = Q, Q
for i in range(self.MAX_ITER):
Xn = A.T * X * A - A.T * X * B * \
la.inv(R + B.T * X * B) * B.T * X * A + Q
if (abs(Xn - X)).max() < self.EPS:
break
X = Xn
return Xn
def dlqr(self, A, B, Q, R):
"""Solve the discrete time lqr controller.
x[k+1] = A x[k] + B u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
# ref Bertsekas, p.151
"""
# first, try to solve the ricatti equation
X = self.solve_dare(A, B, Q, R)
# compute the LQR gain
K = la.inv(B.T @ X @ B + R) @ (B.T @ X @ A)
eigValues = la.eigvals(A - B @ K)
return K, X, eigValues
def get_system_model(self):
A = np.array([[self.DT, 1.0],
[0.0, self.DT]])
B = np.array([0.0, 1.0]).reshape(2, 1)
return A, B
def lqr_control(self, A, B, x):
Kopt, X, ev = self.dlqr(A, B, np.eye(2), np.eye(1))
u = -Kopt @ x
return u
def main():
print(__file__ + " start!!")
ntest = 10 # number of goal
area = 100.0 # sampling area
lqr_planner = LQRPlanner()
for i in range(ntest):
sx = 6.0
sy = 6.0
gx = random.uniform(-area, area)
gy = random.uniform(-area, area)
rx, ry = lqr_planner.lqr_planning(sx, sy, gx, gy, show_animation=SHOW_ANIMATION)
if SHOW_ANIMATION: # pragma: no cover
plt.plot(sx, sy, "or")
plt.plot(gx, gy, "ob")
plt.plot(rx, ry, "-r")
plt.axis("equal")
plt.pause(1.0)
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/LQRPlanner/lqr_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,026 |
```python
"""
Visibility Road Map Planner
author: Atsushi Sakai (@Atsushi_twi)
"""
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from VisibilityRoadMap.geometry import Geometry
from VoronoiRoadMap.dijkstra_search import DijkstraSearch
show_animation = True
class VisibilityRoadMap:
def __init__(self, expand_distance, do_plot=False):
self.expand_distance = expand_distance
self.do_plot = do_plot
def planning(self, start_x, start_y, goal_x, goal_y, obstacles):
nodes = self.generate_visibility_nodes(start_x, start_y,
goal_x, goal_y, obstacles)
road_map_info = self.generate_road_map_info(nodes, obstacles)
if self.do_plot:
self.plot_road_map(nodes, road_map_info)
plt.pause(1.0)
rx, ry = DijkstraSearch(show_animation).search(
start_x, start_y,
goal_x, goal_y,
[node.x for node in nodes],
[node.y for node in nodes],
road_map_info
)
return rx, ry
def generate_visibility_nodes(self, start_x, start_y, goal_x, goal_y,
obstacles):
# add start and goal as nodes
nodes = [DijkstraSearch.Node(start_x, start_y),
DijkstraSearch.Node(goal_x, goal_y, 0, None)]
# add vertexes in configuration space as nodes
for obstacle in obstacles:
cvx_list, cvy_list = self.calc_vertexes_in_configuration_space(
obstacle.x_list, obstacle.y_list)
for (vx, vy) in zip(cvx_list, cvy_list):
nodes.append(DijkstraSearch.Node(vx, vy))
if self.do_plot:
for node in nodes:
plt.plot(node.x, node.y, "xr")
return nodes
def calc_vertexes_in_configuration_space(self, x_list, y_list):
x_list = x_list[0:-1]
y_list = y_list[0:-1]
cvx_list, cvy_list = [], []
n_data = len(x_list)
for index in range(n_data):
offset_x, offset_y = self.calc_offset_xy(
x_list[index - 1], y_list[index - 1],
x_list[index], y_list[index],
x_list[(index + 1) % n_data], y_list[(index + 1) % n_data],
)
cvx_list.append(offset_x)
cvy_list.append(offset_y)
return cvx_list, cvy_list
def generate_road_map_info(self, nodes, obstacles):
road_map_info_list = []
for target_node in nodes:
road_map_info = []
for node_id, node in enumerate(nodes):
if np.hypot(target_node.x - node.x,
target_node.y - node.y) <= 0.1:
continue
is_valid = True
for obstacle in obstacles:
if not self.is_edge_valid(target_node, node, obstacle):
is_valid = False
break
if is_valid:
road_map_info.append(node_id)
road_map_info_list.append(road_map_info)
return road_map_info_list
@staticmethod
def is_edge_valid(target_node, node, obstacle):
for i in range(len(obstacle.x_list) - 1):
p1 = Geometry.Point(target_node.x, target_node.y)
p2 = Geometry.Point(node.x, node.y)
p3 = Geometry.Point(obstacle.x_list[i], obstacle.y_list[i])
p4 = Geometry.Point(obstacle.x_list[i + 1], obstacle.y_list[i + 1])
if Geometry.is_seg_intersect(p1, p2, p3, p4):
return False
return True
def calc_offset_xy(self, px, py, x, y, nx, ny):
p_vec = math.atan2(y - py, x - px)
n_vec = math.atan2(ny - y, nx - x)
offset_vec = math.atan2(math.sin(p_vec) + math.sin(n_vec),
math.cos(p_vec) + math.cos(
n_vec)) + math.pi / 2.0
offset_x = x + self.expand_distance * math.cos(offset_vec)
offset_y = y + self.expand_distance * math.sin(offset_vec)
return offset_x, offset_y
@staticmethod
def plot_road_map(nodes, road_map_info_list):
for i, node in enumerate(nodes):
for index in road_map_info_list[i]:
plt.plot([node.x, nodes[index].x],
[node.y, nodes[index].y], "-b")
class ObstaclePolygon:
def __init__(self, x_list, y_list):
self.x_list = x_list
self.y_list = y_list
self.close_polygon()
self.make_clockwise()
def make_clockwise(self):
if not self.is_clockwise():
self.x_list = list(reversed(self.x_list))
self.y_list = list(reversed(self.y_list))
def is_clockwise(self):
n_data = len(self.x_list)
eval_sum = sum([(self.x_list[i + 1] - self.x_list[i]) *
(self.y_list[i + 1] + self.y_list[i])
for i in range(n_data - 1)])
eval_sum += (self.x_list[0] - self.x_list[n_data - 1]) * \
(self.y_list[0] + self.y_list[n_data - 1])
return eval_sum >= 0
def close_polygon(self):
is_x_same = self.x_list[0] == self.x_list[-1]
is_y_same = self.y_list[0] == self.y_list[-1]
if is_x_same and is_y_same:
return # no need to close
self.x_list.append(self.x_list[0])
self.y_list.append(self.y_list[0])
def plot(self):
plt.plot(self.x_list, self.y_list, "-k")
def main():
print(__file__ + " start!!")
# start and goal position
sx, sy = 10.0, 10.0 # [m]
gx, gy = 50.0, 50.0 # [m]
expand_distance = 5.0 # [m]
obstacles = [
ObstaclePolygon(
[20.0, 30.0, 15.0],
[20.0, 20.0, 30.0],
),
ObstaclePolygon(
[40.0, 45.0, 50.0, 40.0],
[50.0, 40.0, 20.0, 40.0],
),
ObstaclePolygon(
[20.0, 30.0, 30.0, 20.0],
[40.0, 45.0, 60.0, 50.0],
)
]
if show_animation: # pragma: no cover
plt.plot(sx, sy, "or")
plt.plot(gx, gy, "ob")
for ob in obstacles:
ob.plot()
plt.axis("equal")
plt.pause(1.0)
rx, ry = VisibilityRoadMap(expand_distance, do_plot=show_animation)\
.planning(sx, sy, gx, gy, obstacles)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.1)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/VisibilityRoadMap/visibility_road_map.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,673 |
```python
class Geometry:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def is_seg_intersect(p1, q1, p2, q2):
def on_segment(p, q, r):
if ((q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and
(q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))):
return True
return False
def orientation(p, q, r):
val = (float(q.y - p.y) * (r.x - q.x)) - (
float(q.x - p.x) * (r.y - q.y))
if val > 0:
return 1
if val < 0:
return 2
return 0
# Find the 4 orientations required for
# the general and special cases
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
if (o1 != o2) and (o3 != o4):
return True
if (o1 == 0) and on_segment(p1, p2, q1):
return True
if (o2 == 0) and on_segment(p1, q2, q1):
return True
if (o3 == 0) and on_segment(p2, p1, q2):
return True
if (o4 == 0) and on_segment(p2, q1, q2):
return True
return False
``` | /content/code_sandbox/PathPlanning/VisibilityRoadMap/geometry.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 395 |
```python
"""
D* Lite grid planning
author: vss2sn (28676655+vss2sn@users.noreply.github.com)
Link to papers:
D* Lite (Link: path_to_url
Improved Fast Replanning for Robot Navigation in Unknown Terrain
(Link: path_to_url~maxim/files/dlite_icra02.pdf)
Implemented maintaining similarity with the pseudocode for understanding.
Code can be significantly optimized by using a priority queue for U, etc.
Avoiding additional imports based on repository philosophy.
"""
import math
import matplotlib.pyplot as plt
import random
import numpy as np
show_animation = True
pause_time = 0.001
p_create_random_obstacle = 0
class Node:
def __init__(self, x: int = 0, y: int = 0, cost: float = 0.0):
self.x = x
self.y = y
self.cost = cost
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
def compare_coordinates(node1: Node, node2: Node):
return node1.x == node2.x and node1.y == node2.y
class DStarLite:
# Please adjust the heuristic function (h) if you change the list of
# possible motions
motions = [
Node(1, 0, 1),
Node(0, 1, 1),
Node(-1, 0, 1),
Node(0, -1, 1),
Node(1, 1, math.sqrt(2)),
Node(1, -1, math.sqrt(2)),
Node(-1, 1, math.sqrt(2)),
Node(-1, -1, math.sqrt(2))
]
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
def create_grid(self, val: float):
return np.full((self.x_max, self.y_max), val)
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
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
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
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]))
def is_valid(self, node: Node):
if 0 <= node.x < self.x_max and 0 <= node.y < self.y_max:
return True
return False
def get_neighbours(self, u: Node):
return [add_coordinates(u, motion) for motion in self.motions
if self.is_valid(add_coordinates(u, motion))]
def pred(self, u: Node):
# Grid, so each vertex is connected to the ones around it
return self.get_neighbours(u)
def succ(self, u: Node):
# Grid, so each vertex is connected to the ones around it
return self.get_neighbours(u)
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))
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])
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])
def compute_shortest_path(self):
self.U.sort(key=lambda x: x[1])
has_elements = len(self.U) > 0
start_key_not_updated = self.compare_keys(
self.U[0][1], self.calculate_key(self.start)
)
rhs_not_equal_to_g = self.rhs[self.start.x][self.start.y] != \
self.g[self.start.x][self.start.y]
while has_elements and start_key_not_updated or rhs_not_equal_to_g:
self.kold = self.U[0][1]
u = self.U[0][0]
self.U.pop(0)
if self.compare_keys(self.kold, self.calculate_key(u)):
self.U.append((u, self.calculate_key(u)))
self.U.sort(key=lambda x: x[1])
elif (self.g[u.x, u.y] > self.rhs[u.x, u.y]).any():
self.g[u.x, u.y] = self.rhs[u.x, u.y]
for s in self.pred(u):
self.update_vertex(s)
else:
self.g[u.x, u.y] = math.inf
for s in self.pred(u) + [u]:
self.update_vertex(s)
self.U.sort(key=lambda x: x[1])
start_key_not_updated = self.compare_keys(
self.U[0][1], self.calculate_key(self.start)
)
rhs_not_equal_to_g = self.rhs[self.start.x][self.start.y] != \
self.g[self.start.x][self.start.y]
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
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
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
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
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
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)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/PathPlanning/DStarLite/d_star_lite.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 4,137 |
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
class Spline2D:
def __init__(self, x, y, kind="cubic"):
self.s = self.__calc_s(x, y)
self.sx = interpolate.interp1d(self.s, x, kind=kind)
self.sy = interpolate.interp1d(self.s, y, kind=kind)
def __calc_s(self, x, y):
self.ds = np.hypot(np.diff(x), np.diff(y))
s = [0.0]
s.extend(np.cumsum(self.ds))
return s
def calc_position(self, s):
x = self.sx(s)
y = self.sy(s)
return x, y
def main():
x = [-2.5, 0.0, 2.5, 5.0, 7.5, 3.0, -1.0]
y = [0.7, -6, -5, -3.5, 0.0, 5.0, -2.0]
ds = 0.1 # [m] distance of each interpolated points
plt.subplots(1)
plt.plot(x, y, "xb", label="Data points")
for (kind, label) in [("linear", "C0 (Linear spline)"),
("quadratic", "C0 & C1 (Quadratic spline)"),
("cubic", "C0 & C1 & C2 (Cubic spline)")]:
rx, ry = [], []
sp = Spline2D(x, y, kind=kind)
s = np.arange(0, sp.s[-1], ds)
for i_s in s:
ix, iy = sp.calc_position(i_s)
rx.append(ix)
ry.append(iy)
plt.plot(rx, ry, "-", label=label)
plt.grid(True)
plt.axis("equal")
plt.xlabel("x[m]")
plt.ylabel("y[m]")
plt.legend()
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/CubicSpline/spline_continuity.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 457 |
```python
"""
Spiral Spanning Tree Coverage Path Planner
author: Todd Tang
paper: Spiral-STC: An On-Line Coverage Algorithm of Grid Environments
by a Mobile Robot - Gabriely et.al.
link: path_to_url
"""
import os
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
do_animation = True
class SpiralSpanningTreeCoveragePlanner:
def __init__(self, occ_map):
self.origin_map_height = occ_map.shape[0]
self.origin_map_width = occ_map.shape[1]
# original map resolution must be even
if self.origin_map_height % 2 == 1 or self.origin_map_width % 2 == 1:
sys.exit('original map width/height must be even \
in grayscale .png format')
self.occ_map = occ_map
self.merged_map_height = self.origin_map_height // 2
self.merged_map_width = self.origin_map_width // 2
self.edge = []
def plan(self, start):
"""plan
performing Spiral Spanning Tree Coverage path planning
:param start: the start node of Spiral Spanning Tree Coverage
"""
visit_times = np.zeros(
(self.merged_map_height, self.merged_map_width), dtype=int)
visit_times[start[0]][start[1]] = 1
# generate route by
# recusively call perform_spanning_tree_coverage() from start node
route = []
self.perform_spanning_tree_coverage(start, visit_times, route)
path = []
# generate path from route
for idx in range(len(route)-1):
dp = abs(route[idx][0] - route[idx+1][0]) + \
abs(route[idx][1] - route[idx+1][1])
if dp == 0:
# special handle for round-trip path
path.append(self.get_round_trip_path(route[idx-1], route[idx]))
elif dp == 1:
path.append(self.move(route[idx], route[idx+1]))
elif dp == 2:
# special handle for non-adjacent route nodes
mid_node = self.get_intermediate_node(route[idx], route[idx+1])
path.append(self.move(route[idx], mid_node))
path.append(self.move(mid_node, route[idx+1]))
else:
sys.exit('adjacent path node distance larger than 2')
return self.edge, route, path
def perform_spanning_tree_coverage(self, current_node, visit_times, route):
"""perform_spanning_tree_coverage
recursive function for function <plan>
:param current_node: current node
"""
def is_valid_node(i, j):
is_i_valid_bounded = 0 <= i < self.merged_map_height
is_j_valid_bounded = 0 <= j < self.merged_map_width
if is_i_valid_bounded and is_j_valid_bounded:
# free only when the 4 sub-cells are all free
return bool(
self.occ_map[2*i][2*j]
and self.occ_map[2*i+1][2*j]
and self.occ_map[2*i][2*j+1]
and self.occ_map[2*i+1][2*j+1])
return False
# counter-clockwise neighbor finding order
order = [[1, 0], [0, 1], [-1, 0], [0, -1]]
found = False
route.append(current_node)
for inc in order:
ni, nj = current_node[0] + inc[0], current_node[1] + inc[1]
if is_valid_node(ni, nj) and visit_times[ni][nj] == 0:
neighbor_node = (ni, nj)
self.edge.append((current_node, neighbor_node))
found = True
visit_times[ni][nj] += 1
self.perform_spanning_tree_coverage(
neighbor_node, visit_times, route)
# backtrace route from node with neighbors all visited
# to first node with unvisited neighbor
if not found:
has_node_with_unvisited_ngb = False
for node in reversed(route):
# drop nodes that have been visited twice
if visit_times[node[0]][node[1]] == 2:
continue
visit_times[node[0]][node[1]] += 1
route.append(node)
for inc in order:
ni, nj = node[0] + inc[0], node[1] + inc[1]
if is_valid_node(ni, nj) and visit_times[ni][nj] == 0:
has_node_with_unvisited_ngb = True
break
if has_node_with_unvisited_ngb:
break
return route
def move(self, p, q):
direction = self.get_vector_direction(p, q)
# move east
if direction == 'E':
p = self.get_sub_node(p, 'SE')
q = self.get_sub_node(q, 'SW')
# move west
elif direction == 'W':
p = self.get_sub_node(p, 'NW')
q = self.get_sub_node(q, 'NE')
# move south
elif direction == 'S':
p = self.get_sub_node(p, 'SW')
q = self.get_sub_node(q, 'NW')
# move north
elif direction == 'N':
p = self.get_sub_node(p, 'NE')
q = self.get_sub_node(q, 'SE')
else:
sys.exit('move direction error...')
return [p, q]
def get_round_trip_path(self, last, pivot):
direction = self.get_vector_direction(last, pivot)
if direction == 'E':
return [self.get_sub_node(pivot, 'SE'),
self.get_sub_node(pivot, 'NE')]
elif direction == 'S':
return [self.get_sub_node(pivot, 'SW'),
self.get_sub_node(pivot, 'SE')]
elif direction == 'W':
return [self.get_sub_node(pivot, 'NW'),
self.get_sub_node(pivot, 'SW')]
elif direction == 'N':
return [self.get_sub_node(pivot, 'NE'),
self.get_sub_node(pivot, 'NW')]
else:
sys.exit('get_round_trip_path: last->pivot direction error.')
def get_vector_direction(self, p, q):
# east
if p[0] == q[0] and p[1] < q[1]:
return 'E'
# west
elif p[0] == q[0] and p[1] > q[1]:
return 'W'
# south
elif p[0] < q[0] and p[1] == q[1]:
return 'S'
# north
elif p[0] > q[0] and p[1] == q[1]:
return 'N'
else:
sys.exit('get_vector_direction: Only E/W/S/N direction supported.')
def get_sub_node(self, node, direction):
if direction == 'SE':
return [2*node[0]+1, 2*node[1]+1]
elif direction == 'SW':
return [2*node[0]+1, 2*node[1]]
elif direction == 'NE':
return [2*node[0], 2*node[1]+1]
elif direction == 'NW':
return [2*node[0], 2*node[1]]
else:
sys.exit('get_sub_node: sub-node direction error.')
def get_interpolated_path(self, p, q):
# direction p->q: southwest / northeast
if (p[0] < q[0]) ^ (p[1] < q[1]):
ipx = [p[0], p[0], q[0]]
ipy = [p[1], q[1], q[1]]
# direction p->q: southeast / northwest
else:
ipx = [p[0], q[0], q[0]]
ipy = [p[1], p[1], q[1]]
return ipx, ipy
def get_intermediate_node(self, p, q):
p_ngb, q_ngb = set(), set()
for m, n in self.edge:
if m == p:
p_ngb.add(n)
if n == p:
p_ngb.add(m)
if m == q:
q_ngb.add(n)
if n == q:
q_ngb.add(m)
itsc = p_ngb.intersection(q_ngb)
if len(itsc) == 0:
sys.exit('get_intermediate_node: \
no intermediate node between', p, q)
elif len(itsc) == 1:
return list(itsc)[0]
else:
sys.exit('get_intermediate_node: \
more than 1 intermediate node between', p, q)
def visualize_path(self, edge, path, start):
def coord_transform(p):
return [2*p[1] + 0.5, 2*p[0] + 0.5]
if do_animation:
last = path[0][0]
trajectory = [[last[1]], [last[0]]]
for p, q in path:
distance = math.hypot(p[0]-last[0], p[1]-last[1])
if distance <= 1.0:
trajectory[0].append(p[1])
trajectory[1].append(p[0])
else:
ipx, ipy = self.get_interpolated_path(last, p)
trajectory[0].extend(ipy)
trajectory[1].extend(ipx)
last = q
trajectory[0].append(last[1])
trajectory[1].append(last[0])
for idx, state in enumerate(np.transpose(trajectory)):
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])
# draw spanning tree
plt.imshow(self.occ_map, 'gray')
for p, q in edge:
p = coord_transform(p)
q = coord_transform(q)
plt.plot([p[0], q[0]], [p[1], q[1]], '-oc')
sx, sy = coord_transform(start)
plt.plot([sx], [sy], 'pr', markersize=10)
# draw move path
plt.plot(trajectory[0][:idx+1], trajectory[1][:idx+1], '-k')
plt.plot(state[0], state[1], 'or')
plt.axis('equal')
plt.grid(True)
plt.pause(0.01)
else:
# draw spanning tree
plt.imshow(self.occ_map, 'gray')
for p, q in edge:
p = coord_transform(p)
q = coord_transform(q)
plt.plot([p[0], q[0]], [p[1], q[1]], '-oc')
sx, sy = coord_transform(start)
plt.plot([sx], [sy], 'pr', markersize=10)
# draw move path
last = path[0][0]
for p, q in path:
distance = math.hypot(p[0]-last[0], p[1]-last[1])
if distance == 1.0:
plt.plot([last[1], p[1]], [last[0], p[0]], '-k')
else:
ipx, ipy = self.get_interpolated_path(last, p)
plt.plot(ipy, ipx, '-k')
plt.arrow(p[1], p[0], q[1]-p[1], q[0]-p[0], head_width=0.2)
last = q
plt.show()
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
img = plt.imread(os.path.join(dir_path, 'map', 'test_2.png'))
STC_planner = SpiralSpanningTreeCoveragePlanner(img)
start = (10, 0)
edge, route, path = STC_planner.plan(start)
STC_planner.visualize_path(edge, path, start)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/PathPlanning/SpiralSpanningTreeCPP/spiral_spanning_tree_coverage_path_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,731 |
```python
"""
Cubic spline planner
Author: Atsushi Sakai(@Atsushi_twi)
"""
import math
import numpy as np
import bisect
class CubicSpline1D:
"""
1D Cubic Spline class
Parameters
----------
x : list
x coordinates for data points. This x coordinates must be
sorted
in ascending order.
y : list
y coordinates for data points
Examples
--------
You can interpolate 1D data points.
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.arange(5)
>>> y = [1.7, -6, 5, 6.5, 0.0]
>>> sp = CubicSpline1D(x, y)
>>> xi = np.linspace(0.0, 5.0)
>>> yi = [sp.calc_position(x) for x in xi]
>>> plt.plot(x, y, "xb", label="Data points")
>>> plt.plot(xi, yi , "r", label="Cubic spline interpolation")
>>> plt.grid(True)
>>> plt.legend()
>>> plt.show()
.. image:: cubic_spline_1d.png
"""
def __init__(self, x, y):
h = np.diff(x)
if np.any(h < 0):
raise ValueError("x coordinates must be sorted in ascending order")
self.a, self.b, self.c, self.d = [], [], [], []
self.x = x
self.y = y
self.nx = len(x) # dimension of x
# calc coefficient a
self.a = [iy for iy in y]
# calc coefficient c
A = self.__calc_A(h)
B = self.__calc_B(h, self.a)
self.c = np.linalg.solve(A, B)
# calc spline coefficient b and d
for i in range(self.nx - 1):
d = (self.c[i + 1] - self.c[i]) / (3.0 * h[i])
b = 1.0 / h[i] * (self.a[i + 1] - self.a[i]) \
- h[i] / 3.0 * (2.0 * self.c[i] + self.c[i + 1])
self.d.append(d)
self.b.append(b)
def calc_position(self, x):
"""
Calc `y` position for given `x`.
if `x` is outside the data point's `x` range, return None.
Returns
-------
y : float
y position for given x.
"""
if x < self.x[0]:
return None
elif x > self.x[-1]:
return None
i = self.__search_index(x)
dx = x - self.x[i]
position = self.a[i] + self.b[i] * dx + \
self.c[i] * dx ** 2.0 + self.d[i] * dx ** 3.0
return position
def calc_first_derivative(self, x):
"""
Calc first derivative at given x.
if x is outside the input x, return None
Returns
-------
dy : float
first derivative for given x.
"""
if x < self.x[0]:
return None
elif x > self.x[-1]:
return None
i = self.__search_index(x)
dx = x - self.x[i]
dy = self.b[i] + 2.0 * self.c[i] * dx + 3.0 * self.d[i] * dx ** 2.0
return dy
def calc_second_derivative(self, x):
"""
Calc second derivative at given x.
if x is outside the input x, return None
Returns
-------
ddy : float
second derivative for given x.
"""
if x < self.x[0]:
return None
elif x > self.x[-1]:
return None
i = self.__search_index(x)
dx = x - self.x[i]
ddy = 2.0 * self.c[i] + 6.0 * self.d[i] * dx
return ddy
def __search_index(self, x):
"""
search data segment index
"""
return bisect.bisect(self.x, x) - 1
def __calc_A(self, h):
"""
calc matrix A for spline coefficient c
"""
A = np.zeros((self.nx, self.nx))
A[0, 0] = 1.0
for i in range(self.nx - 1):
if i != (self.nx - 2):
A[i + 1, i + 1] = 2.0 * (h[i] + h[i + 1])
A[i + 1, i] = h[i]
A[i, i + 1] = h[i]
A[0, 1] = 0.0
A[self.nx - 1, self.nx - 2] = 0.0
A[self.nx - 1, self.nx - 1] = 1.0
return A
def __calc_B(self, h, a):
"""
calc matrix B for spline coefficient c
"""
B = np.zeros(self.nx)
for i in range(self.nx - 2):
B[i + 1] = 3.0 * (a[i + 2] - a[i + 1]) / h[i + 1]\
- 3.0 * (a[i + 1] - a[i]) / h[i]
return B
class CubicSpline2D:
"""
Cubic CubicSpline2D class
Parameters
----------
x : list
x coordinates for data points.
y : list
y coordinates for data points.
Examples
--------
You can interpolate a 2D data points.
>>> import matplotlib.pyplot as plt
>>> x = [-2.5, 0.0, 2.5, 5.0, 7.5, 3.0, -1.0]
>>> y = [0.7, -6, 5, 6.5, 0.0, 5.0, -2.0]
>>> ds = 0.1 # [m] distance of each interpolated points
>>> sp = CubicSpline2D(x, y)
>>> s = np.arange(0, sp.s[-1], ds)
>>> rx, ry, ryaw, rk = [], [], [], []
>>> for i_s in s:
... ix, iy = sp.calc_position(i_s)
... rx.append(ix)
... ry.append(iy)
... ryaw.append(sp.calc_yaw(i_s))
... rk.append(sp.calc_curvature(i_s))
>>> plt.subplots(1)
>>> plt.plot(x, y, "xb", label="Data points")
>>> plt.plot(rx, ry, "-r", label="Cubic spline path")
>>> plt.grid(True)
>>> plt.axis("equal")
>>> plt.xlabel("x[m]")
>>> plt.ylabel("y[m]")
>>> plt.legend()
>>> plt.show()
.. image:: cubic_spline_2d_path.png
>>> plt.subplots(1)
>>> plt.plot(s, [np.rad2deg(iyaw) for iyaw in ryaw], "-r", label="yaw")
>>> plt.grid(True)
>>> plt.legend()
>>> plt.xlabel("line length[m]")
>>> plt.ylabel("yaw angle[deg]")
.. image:: cubic_spline_2d_yaw.png
>>> plt.subplots(1)
>>> plt.plot(s, rk, "-r", label="curvature")
>>> plt.grid(True)
>>> plt.legend()
>>> plt.xlabel("line length[m]")
>>> plt.ylabel("curvature [1/m]")
.. image:: cubic_spline_2d_curvature.png
"""
def __init__(self, x, y):
self.s = self.__calc_s(x, y)
self.sx = CubicSpline1D(self.s, x)
self.sy = CubicSpline1D(self.s, y)
def __calc_s(self, x, y):
dx = np.diff(x)
dy = np.diff(y)
self.ds = np.hypot(dx, dy)
s = [0]
s.extend(np.cumsum(self.ds))
return s
def calc_position(self, s):
"""
calc position
Parameters
----------
s : float
distance from the start point. if `s` is outside the data point's
range, return None.
Returns
-------
x : float
x position for given s.
y : float
y position for given s.
"""
x = self.sx.calc_position(s)
y = self.sy.calc_position(s)
return x, y
def calc_curvature(self, s):
"""
calc curvature
Parameters
----------
s : float
distance from the start point. if `s` is outside the data point's
range, return None.
Returns
-------
k : float
curvature for given s.
"""
dx = self.sx.calc_first_derivative(s)
ddx = self.sx.calc_second_derivative(s)
dy = self.sy.calc_first_derivative(s)
ddy = self.sy.calc_second_derivative(s)
k = (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))
return k
def calc_yaw(self, s):
"""
calc yaw
Parameters
----------
s : float
distance from the start point. if `s` is outside the data point's
range, return None.
Returns
-------
yaw : float
yaw angle (tangent vector) for given s.
"""
dx = self.sx.calc_first_derivative(s)
dy = self.sy.calc_first_derivative(s)
yaw = math.atan2(dy, dx)
return yaw
def calc_spline_course(x, y, ds=0.1):
sp = CubicSpline2D(x, y)
s = list(np.arange(0, sp.s[-1], ds))
rx, ry, ryaw, rk = [], [], [], []
for i_s in s:
ix, iy = sp.calc_position(i_s)
rx.append(ix)
ry.append(iy)
ryaw.append(sp.calc_yaw(i_s))
rk.append(sp.calc_curvature(i_s))
return rx, ry, ryaw, rk, s
def main_1d():
print("CubicSpline1D test")
import matplotlib.pyplot as plt
x = np.arange(5)
y = [1.7, -6, 5, 6.5, 0.0]
sp = CubicSpline1D(x, y)
xi = np.linspace(0.0, 5.0)
plt.plot(x, y, "xb", label="Data points")
plt.plot(xi, [sp.calc_position(x) for x in xi], "r",
label="Cubic spline interpolation")
plt.grid(True)
plt.legend()
plt.show()
def main_2d(): # pragma: no cover
print("CubicSpline1D 2D test")
import matplotlib.pyplot as plt
x = [-2.5, 0.0, 2.5, 5.0, 7.5, 3.0, -1.0]
y = [0.7, -6, 5, 6.5, 0.0, 5.0, -2.0]
ds = 0.1 # [m] distance of each interpolated points
sp = CubicSpline2D(x, y)
s = np.arange(0, sp.s[-1], ds)
rx, ry, ryaw, rk = [], [], [], []
for i_s in s:
ix, iy = sp.calc_position(i_s)
rx.append(ix)
ry.append(iy)
ryaw.append(sp.calc_yaw(i_s))
rk.append(sp.calc_curvature(i_s))
plt.subplots(1)
plt.plot(x, y, "xb", label="Data points")
plt.plot(rx, ry, "-r", label="Cubic spline path")
plt.grid(True)
plt.axis("equal")
plt.xlabel("x[m]")
plt.ylabel("y[m]")
plt.legend()
plt.subplots(1)
plt.plot(s, [np.rad2deg(iyaw) for iyaw in ryaw], "-r", label="yaw")
plt.grid(True)
plt.legend()
plt.xlabel("line length[m]")
plt.ylabel("yaw angle[deg]")
plt.subplots(1)
plt.plot(s, rk, "-r", label="curvature")
plt.grid(True)
plt.legend()
plt.xlabel("line length[m]")
plt.ylabel("curvature [1/m]")
plt.show()
if __name__ == '__main__':
# main_1d()
main_2d()
``` | /content/code_sandbox/PathPlanning/CubicSpline/cubic_spline_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,918 |
```python
"""
Dijkstra Search library
author: Atsushi Sakai (@Atsushi_twi)
"""
import matplotlib.pyplot as plt
import math
import numpy as np
class DijkstraSearch:
class Node:
"""
Node class for dijkstra search
"""
def __init__(self, x, y, cost=None, parent=None, edge_ids=None):
self.x = x
self.y = y
self.cost = cost
self.parent = parent
self.edge_ids = edge_ids
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent)
def __init__(self, show_animation):
self.show_animation = show_animation
def search(self, sx, sy, gx, gy, node_x, node_y, edge_ids_list):
"""
Search shortest path
s_x: start x positions [m]
s_y: start y positions [m]
gx: goal x position [m]
gx: goal x position [m]
node_x: node x position
node_y: node y position
edge_ids_list: edge_list each item includes a list of edge ids
"""
start_node = self.Node(sx, sy, 0.0, -1)
goal_node = self.Node(gx, gy, 0.0, -1)
current_node = None
open_set, close_set = dict(), dict()
open_set[self.find_id(node_x, node_y, start_node)] = start_node
while True:
if self.has_node_in_set(close_set, goal_node):
print("goal is found!")
goal_node.parent = current_node.parent
goal_node.cost = current_node.cost
break
elif not open_set:
print("Cannot find path")
break
current_id = min(open_set, key=lambda o: open_set[o].cost)
current_node = open_set[current_id]
# show graph
if self.show_animation and len(
close_set.keys()) % 2 == 0: # pragma: no cover
plt.plot(current_node.x, current_node.y, "xg")
# 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.pause(0.1)
# Remove the item from the open set
del open_set[current_id]
# Add it to the closed set
close_set[current_id] = current_node
# expand search grid based on motion model
for i in range(len(edge_ids_list[current_id])):
n_id = edge_ids_list[current_id][i]
dx = node_x[n_id] - current_node.x
dy = node_y[n_id] - current_node.y
d = math.hypot(dx, dy)
node = self.Node(node_x[n_id], node_y[n_id],
current_node.cost + d, current_id)
if n_id in close_set:
continue
# Otherwise if it is already in the open set
if n_id in open_set:
if open_set[n_id].cost > node.cost:
open_set[n_id] = node
else:
open_set[n_id] = node
# generate final course
rx, ry = self.generate_final_path(close_set, goal_node)
return rx, ry
@staticmethod
def generate_final_path(close_set, goal_node):
rx, ry = [goal_node.x], [goal_node.y]
parent = goal_node.parent
while parent != -1:
n = close_set[parent]
rx.append(n.x)
ry.append(n.y)
parent = n.parent
rx, ry = rx[::-1], ry[::-1] # reverse it
return rx, ry
def has_node_in_set(self, target_set, node):
for key in target_set:
if self.is_same_node(target_set[key], node):
return True
return False
def find_id(self, node_x_list, node_y_list, target_node):
for i, _ in enumerate(node_x_list):
if self.is_same_node_with_xy(node_x_list[i], node_y_list[i],
target_node):
return i
return None
@staticmethod
def is_same_node_with_xy(node_x, node_y, node_b):
dist = np.hypot(node_x - node_b.x,
node_y - node_b.y)
return dist <= 0.1
@staticmethod
def is_same_node(node_a, node_b):
dist = np.hypot(node_a.x - node_b.x,
node_a.y - node_b.y)
return dist <= 0.1
``` | /content/code_sandbox/PathPlanning/VoronoiRoadMap/dijkstra_search.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,042 |
```python
"""
Voronoi Road Map Planner
author: Atsushi Sakai (@Atsushi_twi)
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import cKDTree, Voronoi
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from VoronoiRoadMap.dijkstra_search import DijkstraSearch
show_animation = True
class VoronoiRoadMapPlanner:
def __init__(self):
# parameter
self.N_KNN = 10 # number of edge from one sampled point
self.MAX_EDGE_LEN = 30.0 # [m] Maximum edge length
def planning(self, sx, sy, gx, gy, ox, oy, robot_radius):
obstacle_tree = cKDTree(np.vstack((ox, oy)).T)
sample_x, sample_y = self.voronoi_sampling(sx, sy, gx, gy, ox, oy)
if show_animation: # pragma: no cover
plt.plot(sample_x, sample_y, ".b")
road_map_info = self.generate_road_map_info(
sample_x, sample_y, robot_radius, obstacle_tree)
rx, ry = DijkstraSearch(show_animation).search(sx, sy, gx, gy,
sample_x, sample_y,
road_map_info)
return rx, ry
def is_collision(self, sx, sy, gx, gy, rr, obstacle_kd_tree):
x = sx
y = sy
dx = gx - sx
dy = gy - sy
yaw = math.atan2(gy - sy, gx - sx)
d = math.hypot(dx, dy)
if d >= self.MAX_EDGE_LEN:
return True
D = rr
n_step = round(d / D)
for i in range(n_step):
dist, _ = obstacle_kd_tree.query([x, y])
if dist <= rr:
return True # collision
x += D * math.cos(yaw)
y += D * math.sin(yaw)
# goal point check
dist, _ = obstacle_kd_tree.query([gx, gy])
if dist <= rr:
return True # collision
return False # OK
def generate_road_map_info(self, node_x, node_y, rr, obstacle_tree):
"""
Road map generation
node_x: [m] x positions of sampled points
node_y: [m] y positions of sampled points
rr: Robot Radius[m]
obstacle_tree: KDTree object of obstacles
"""
road_map = []
n_sample = len(node_x)
node_tree = cKDTree(np.vstack((node_x, node_y)).T)
for (i, ix, iy) in zip(range(n_sample), node_x, node_y):
dists, indexes = node_tree.query([ix, iy], k=n_sample)
edge_id = []
for ii in range(1, len(indexes)):
nx = node_x[indexes[ii]]
ny = node_y[indexes[ii]]
if not self.is_collision(ix, iy, nx, ny, rr, obstacle_tree):
edge_id.append(indexes[ii])
if len(edge_id) >= self.N_KNN:
break
road_map.append(edge_id)
# plot_road_map(road_map, sample_x, sample_y)
return road_map
@staticmethod
def plot_road_map(road_map, sample_x, sample_y): # pragma: no cover
for i, _ in enumerate(road_map):
for ii in range(len(road_map[i])):
ind = road_map[i][ii]
plt.plot([sample_x[i], sample_x[ind]],
[sample_y[i], sample_y[ind]], "-k")
@staticmethod
def voronoi_sampling(sx, sy, gx, gy, ox, oy):
oxy = np.vstack((ox, oy)).T
# generate voronoi point
vor = Voronoi(oxy)
sample_x = [ix for [ix, _] in vor.vertices]
sample_y = [iy for [_, iy] in vor.vertices]
sample_x.append(sx)
sample_y.append(sy)
sample_x.append(gx)
sample_y.append(gy)
return sample_x, sample_y
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
robot_size = 5.0 # [m]
ox = []
oy = []
for i in range(60):
ox.append(i)
oy.append(0.0)
for i in range(60):
ox.append(60.0)
oy.append(i)
for i in range(61):
ox.append(i)
oy.append(60.0)
for i in range(61):
ox.append(0.0)
oy.append(i)
for i in range(40):
ox.append(20.0)
oy.append(i)
for i in range(40):
ox.append(40.0)
oy.append(60.0 - i)
if show_animation: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "^r")
plt.plot(gx, gy, "^c")
plt.grid(True)
plt.axis("equal")
rx, ry = VoronoiRoadMapPlanner().planning(sx, sy, gx, gy, ox, oy,
robot_size)
assert rx, 'Cannot found path'
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.1)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/VoronoiRoadMap/voronoi_road_map.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,301 |
```python
"""
Bidirectional Breadth-First grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class BidirectionalBreadthFirstSearchPlanner:
def __init__(self, ox, oy, resolution, rr):
"""
Initialize grid map for bfs planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.min_x, self.min_y = None, None
self.max_x, self.max_y = None, None
self.x_width, self.y_width, self.obstacle_map = None, None, None
self.resolution = resolution
self.rr = rr
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, parent_index, parent):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
self.parent = parent
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
Bidirectional Breadth First search based planning
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1,
None)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1,
None)
open_set_A, closed_set_A = dict(), dict()
open_set_B, closed_set_B = dict(), dict()
open_set_B[self.calc_grid_index(goal_node)] = goal_node
open_set_A[self.calc_grid_index(start_node)] = start_node
meet_point_A, meet_point_B = None, None
while True:
if len(open_set_A) == 0:
print("Open set A is empty..")
break
if len(open_set_B) == 0:
print("Open set B is empty")
break
current_A = open_set_A.pop(list(open_set_A.keys())[0])
current_B = open_set_B.pop(list(open_set_B.keys())[0])
c_id_A = self.calc_grid_index(current_A)
c_id_B = self.calc_grid_index(current_B)
closed_set_A[c_id_A] = current_A
closed_set_B[c_id_B] = current_B
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current_A.x, self.min_x),
self.calc_grid_position(current_A.y, self.min_y),
"xc")
plt.plot(self.calc_grid_position(current_B.x, self.min_x),
self.calc_grid_position(current_B.y, self.min_y),
"xc")
# 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 len(closed_set_A.keys()) % 10 == 0:
plt.pause(0.001)
if c_id_A in closed_set_B:
print("Find goal")
meet_point_A = closed_set_A[c_id_A]
meet_point_B = closed_set_B[c_id_A]
break
elif c_id_B in closed_set_A:
print("Find goal")
meet_point_A = closed_set_A[c_id_B]
meet_point_B = closed_set_B[c_id_B]
break
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
breakA = False
breakB = False
node_A = self.Node(current_A.x + self.motion[i][0],
current_A.y + self.motion[i][1],
current_A.cost + self.motion[i][2],
c_id_A, None)
node_B = self.Node(current_B.x + self.motion[i][0],
current_B.y + self.motion[i][1],
current_B.cost + self.motion[i][2],
c_id_B, None)
n_id_A = self.calc_grid_index(node_A)
n_id_B = self.calc_grid_index(node_B)
# If the node is not safe, do nothing
if not self.verify_node(node_A):
breakA = True
if not self.verify_node(node_B):
breakB = True
if (n_id_A not in closed_set_A) and \
(n_id_A not in open_set_A) and (not breakA):
node_A.parent = current_A
open_set_A[n_id_A] = node_A
if (n_id_B not in closed_set_B) and \
(n_id_B not in open_set_B) and (not breakB):
node_B.parent = current_B
open_set_B[n_id_B] = node_B
rx, ry = self.calc_final_path_bidir(
meet_point_A, meet_point_B, closed_set_A, closed_set_B)
return rx, ry
# takes both set and meeting nodes and calculate optimal path
def calc_final_path_bidir(self, n1, n2, setA, setB):
rxA, ryA = self.calc_final_path(n1, setA)
rxB, ryB = self.calc_final_path(n2, setB)
rxA.reverse()
ryA.reverse()
rx = rxA + rxB
ry = ryA + ryB
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
self.calc_grid_position(goal_node.y, self.min_y)]
n = closed_set[goal_node.parent_index]
while n is not None:
rx.append(self.calc_grid_position(n.x, self.min_x))
ry.append(self.calc_grid_position(n.y, self.min_y))
n = n.parent
return rx, ry
def calc_grid_position(self, index, min_position):
"""
calc grid position
:param index:
:param min_position:
:return:
"""
pos = index * self.resolution + min_position
return pos
def calc_xy_index(self, position, min_pos):
return round((position - min_pos) / self.resolution)
def calc_grid_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.min_x)
py = self.calc_grid_position(node.y, self.min_y)
if px < self.min_x:
return False
elif py < self.min_y:
return False
elif px >= self.max_x:
return False
elif py >= self.max_y:
return False
# collision check
if self.obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
# obstacle map generation
self.obstacle_map = [[False for _ in range(self.y_width)]
for _ in range(self.x_width)]
for ix in range(self.x_width):
x = self.calc_grid_position(ix, self.min_x)
for iy in range(self.y_width):
y = self.calc_grid_position(iy, self.min_y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obstacle_map[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "ob")
plt.grid(True)
plt.axis("equal")
bi_bfs = BidirectionalBreadthFirstSearchPlanner(
ox, oy, grid_size, robot_radius)
rx, ry = bi_bfs.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/BidirectionalBreadthFirstSearch/bidirectional_breadth_first_search.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,462 |
```python
"""
Depth-First grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class DepthFirstSearchPlanner:
def __init__(self, ox, oy, reso, rr):
"""
Initialize grid map for Depth-First planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.reso = reso
self.rr = rr
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, parent_index, parent):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
self.parent = parent
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
Depth First search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
nstart = self.Node(self.calc_xyindex(sx, self.minx),
self.calc_xyindex(sy, self.miny), 0.0, -1, None)
ngoal = self.Node(self.calc_xyindex(gx, self.minx),
self.calc_xyindex(gy, self.miny), 0.0, -1, None)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(nstart)] = nstart
while True:
if len(open_set) == 0:
print("Open set is empty..")
break
current = open_set.pop(list(open_set.keys())[-1])
c_id = self.calc_grid_index(current)
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current.x, self.minx),
self.calc_grid_position(current.y, self.miny), "xc")
# 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.pause(0.01)
if current.x == ngoal.x and current.y == ngoal.y:
print("Find goal")
ngoal.parent_index = current.parent_index
ngoal.cost = current.cost
break
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2], c_id, None)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if n_id not in closed_set:
open_set[n_id] = node
closed_set[n_id] = node
node.parent = current
rx, ry = self.calc_final_path(ngoal, closed_set)
return rx, ry
def calc_final_path(self, ngoal, closedset):
# generate final course
rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
self.calc_grid_position(ngoal.y, self.miny)]
n = closedset[ngoal.parent_index]
while n is not None:
rx.append(self.calc_grid_position(n.x, self.minx))
ry.append(self.calc_grid_position(n.y, self.miny))
n = n.parent
return rx, ry
def calc_grid_position(self, index, minp):
"""
calc grid position
:param index:
:param minp:
:return:
"""
pos = index * self.reso + minp
return pos
def calc_xyindex(self, position, min_pos):
return round((position - min_pos) / self.reso)
def calc_grid_index(self, node):
return (node.y - self.miny) * self.xwidth + (node.x - self.minx)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.minx)
py = self.calc_grid_position(node.y, self.miny)
if px < self.minx:
return False
elif py < self.miny:
return False
elif px >= self.maxx:
return False
elif py >= self.maxy:
return False
# collision check
if self.obmap[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.minx = round(min(ox))
self.miny = round(min(oy))
self.maxx = round(max(ox))
self.maxy = round(max(oy))
print("min_x:", self.minx)
print("min_y:", self.miny)
print("max_x:", self.maxx)
print("max_y:", self.maxy)
self.xwidth = round((self.maxx - self.minx) / self.reso)
self.ywidth = round((self.maxy - self.miny) / self.reso)
print("x_width:", self.xwidth)
print("y_width:", self.ywidth)
# obstacle map generation
self.obmap = [[False for _ in range(self.ywidth)]
for _ in range(self.xwidth)]
for ix in range(self.xwidth):
x = self.calc_grid_position(ix, self.minx)
for iy in range(self.ywidth):
y = self.calc_grid_position(iy, self.miny)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obmap[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
dfs = DepthFirstSearchPlanner(ox, oy, grid_size, robot_radius)
rx, ry = dfs.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/DepthFirstSearch/depth_first_search.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,902 |
```python
"""
Path planning Sample Code with RRT with Reeds-Shepp path
author: AtsushiSakai(@Atsushi_twi)
"""
import copy
import math
import random
import sys
import pathlib
import matplotlib.pyplot as plt
import numpy as np
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from ReedsSheppPath import reeds_shepp_path_planning
from RRTStar.rrt_star import RRTStar
show_animation = True
class RRTStarReedsShepp(RRTStar):
"""
Class for RRT star planning with Reeds Shepp path
"""
class Node(RRTStar.Node):
"""
RRT Node
"""
def __init__(self, x, y, yaw):
super().__init__(x, y)
self.yaw = yaw
self.path_yaw = []
def __init__(self, start, goal, obstacle_list, rand_area,
max_iter=200, step_size=0.2,
connect_circle_dist=50.0,
robot_radius=0.0
):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1], start[2])
self.end = self.Node(goal[0], goal[1], goal[2])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.max_iter = max_iter
self.step_size = step_size
self.obstacle_list = obstacle_list
self.connect_circle_dist = connect_circle_dist
self.robot_radius = robot_radius
self.curvature = 1.0
self.goal_yaw_th = np.deg2rad(1.0)
self.goal_xy_th = 0.5
def set_random_seed(self, seed):
random.seed(seed)
def planning(self, animation=True, search_until_max_iter=True):
"""
planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind], rnd)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
near_indexes = self.find_near_nodes(new_node)
new_node = self.choose_parent(new_node, near_indexes)
if new_node:
self.node_list.append(new_node)
self.rewire(new_node, near_indexes)
self.try_goal_path(new_node)
if animation and i % 5 == 0:
self.plot_start_goal_arrow()
self.draw_graph(rnd)
if (not search_until_max_iter) and new_node: # check reaching the goal
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index:
return self.generate_final_course(last_index)
else:
print("Cannot find path")
return None
def try_goal_path(self, node):
goal = self.Node(self.end.x, self.end.y, self.end.yaw)
new_node = self.steer(node, goal)
if new_node is None:
return
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
self.node_list.append(new_node)
def draw_graph(self, rnd=None):
plt.clf()
# 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 rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
self.plot_start_goal_arrow()
plt.pause(0.01)
def plot_start_goal_arrow(self):
reeds_shepp_path_planning.plot_arrow(
self.start.x, self.start.y, self.start.yaw)
reeds_shepp_path_planning.plot_arrow(
self.end.x, self.end.y, self.end.yaw)
def steer(self, from_node, to_node):
px, py, pyaw, mode, course_lengths = reeds_shepp_path_planning.reeds_shepp_path_planning(
from_node.x, from_node.y, from_node.yaw, to_node.x,
to_node.y, to_node.yaw, self.curvature, self.step_size)
if not px:
return None
new_node = copy.deepcopy(from_node)
new_node.x = px[-1]
new_node.y = py[-1]
new_node.yaw = pyaw[-1]
new_node.path_x = px
new_node.path_y = py
new_node.path_yaw = pyaw
new_node.cost += sum([abs(l) for l in course_lengths])
new_node.parent = from_node
return new_node
def calc_new_cost(self, from_node, to_node):
_, _, _, _, course_lengths = reeds_shepp_path_planning.reeds_shepp_path_planning(
from_node.x, from_node.y, from_node.yaw, to_node.x,
to_node.y, to_node.yaw, self.curvature, self.step_size)
if not course_lengths:
return float("inf")
return from_node.cost + sum([abs(l) for l in course_lengths])
def get_random_node(self):
rnd = self.Node(random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand),
random.uniform(-math.pi, math.pi)
)
return rnd
def search_best_goal_node(self):
goal_indexes = []
for (i, node) in enumerate(self.node_list):
if self.calc_dist_to_goal(node.x, node.y) <= self.goal_xy_th:
goal_indexes.append(i)
print("goal_indexes:", len(goal_indexes))
# angle check
final_goal_indexes = []
for i in goal_indexes:
if abs(self.node_list[i].yaw - self.end.yaw) <= self.goal_yaw_th:
final_goal_indexes.append(i)
print("final_goal_indexes:", len(final_goal_indexes))
if not final_goal_indexes:
return None
min_cost = min([self.node_list[i].cost for i in final_goal_indexes])
print("min_cost:", min_cost)
for i in final_goal_indexes:
if self.node_list[i].cost == min_cost:
return i
return None
def generate_final_course(self, goal_index):
path = [[self.end.x, self.end.y, self.end.yaw]]
node = self.node_list[goal_index]
while node.parent:
for (ix, iy, iyaw) in zip(reversed(node.path_x), reversed(node.path_y), reversed(node.path_yaw)):
path.append([ix, iy, iyaw])
node = node.parent
path.append([self.start.x, self.start.y, self.start.yaw])
return path
def main(max_iter=100):
print("Start " + __file__)
# ====Search Path with RRT====
obstacleList = [
(5, 5, 1),
(4, 6, 1),
(4, 8, 1),
(4, 10, 1),
(6, 5, 1),
(7, 5, 1),
(8, 6, 1),
(8, 8, 1),
(8, 10, 1)
] # [x,y,size(radius)]
# Set Initial parameters
start = [0.0, 0.0, np.deg2rad(0.0)]
goal = [6.0, 7.0, np.deg2rad(90.0)]
rrt_star_reeds_shepp = RRTStarReedsShepp(start, goal,
obstacleList,
[-2.0, 15.0], max_iter=max_iter)
path = rrt_star_reeds_shepp.planning(animation=show_animation)
# Draw final path
if path and show_animation: # pragma: no cover
rrt_star_reeds_shepp.draw_graph()
plt.plot([x for (x, y, yaw) in path], [y for (x, y, yaw) in path], '-r')
plt.grid(True)
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRTStarReedsShepp/rrt_star_reeds_shepp.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,034 |
```python
"""
Clothoid Path Planner
Author: Daniel Ingram (daniel-s-ingram)
Atsushi Sakai (AtsushiSakai)
Reference paper: Fast and accurate G1 fitting of clothoid curves
path_to_url
"""
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate
from scipy.optimize import fsolve
from math import atan2, cos, hypot, pi, sin
from matplotlib import animation
Point = namedtuple("Point", ["x", "y"])
show_animation = True
def generate_clothoid_paths(start_point, start_yaw_list,
goal_point, goal_yaw_list,
n_path_points):
"""
Generate clothoid path list. This function generate multiple clothoid paths
from multiple orientations(yaw) at start points to multiple orientations
(yaw) at goal point.
:param start_point: Start point of the path
:param start_yaw_list: Orientation list at start point in radian
:param goal_point: Goal point of the path
:param goal_yaw_list: Orientation list at goal point in radian
:param n_path_points: number of path points
:return: clothoid path list
"""
clothoids = []
for start_yaw in start_yaw_list:
for goal_yaw in goal_yaw_list:
clothoid = generate_clothoid_path(start_point, start_yaw,
goal_point, goal_yaw,
n_path_points)
clothoids.append(clothoid)
return clothoids
def generate_clothoid_path(start_point, start_yaw,
goal_point, goal_yaw, n_path_points):
"""
Generate a clothoid path list.
:param start_point: Start point of the path
:param start_yaw: Orientation at start point in radian
:param goal_point: Goal point of the path
:param goal_yaw: Orientation at goal point in radian
:param n_path_points: number of path points
:return: a clothoid path
"""
dx = goal_point.x - start_point.x
dy = goal_point.y - start_point.y
r = hypot(dx, dy)
phi = atan2(dy, dx)
phi1 = normalize_angle(start_yaw - phi)
phi2 = normalize_angle(goal_yaw - phi)
delta = phi2 - phi1
try:
# Step1: Solve g function
A = solve_g_for_root(phi1, phi2, delta)
# Step2: Calculate path parameters
L = compute_path_length(r, phi1, delta, A)
curvature = compute_curvature(delta, A, L)
curvature_rate = compute_curvature_rate(A, L)
except Exception as e:
print(f"Failed to generate clothoid points: {e}")
return None
# Step3: Construct a path with Fresnel integral
points = []
for s in np.linspace(0, L, n_path_points):
try:
x = start_point.x + s * X(curvature_rate * s ** 2, curvature * s,
start_yaw)
y = start_point.y + s * Y(curvature_rate * s ** 2, curvature * s,
start_yaw)
points.append(Point(x, y))
except Exception as e:
print(f"Skipping failed clothoid point: {e}")
return points
def X(a, b, c):
return integrate.quad(lambda t: cos((a/2)*t**2 + b*t + c), 0, 1)[0]
def Y(a, b, c):
return integrate.quad(lambda t: sin((a/2)*t**2 + b*t + c), 0, 1)[0]
def solve_g_for_root(theta1, theta2, delta):
initial_guess = 3*(theta1 + theta2)
return fsolve(lambda A: Y(2*A, delta - A, theta1), [initial_guess])
def compute_path_length(r, theta1, delta, A):
return r / X(2*A, delta - A, theta1)
def compute_curvature(delta, A, L):
return (delta - A) / L
def compute_curvature_rate(A, L):
return 2 * A / (L**2)
def normalize_angle(angle_rad):
return (angle_rad + pi) % (2 * pi) - pi
def get_axes_limits(clothoids):
x_vals = [p.x for clothoid in clothoids for p in clothoid]
y_vals = [p.y for clothoid in clothoids for p in clothoid]
x_min = min(x_vals)
x_max = max(x_vals)
y_min = min(y_vals)
y_max = max(y_vals)
x_offset = 0.1*(x_max - x_min)
y_offset = 0.1*(y_max - y_min)
x_min = x_min - x_offset
x_max = x_max + x_offset
y_min = y_min - y_offset
y_max = y_max + y_offset
return x_min, x_max, y_min, y_max
def draw_clothoids(start, goal, num_steps, clothoidal_paths,
save_animation=False):
fig = plt.figure(figsize=(10, 10))
x_min, x_max, y_min, y_max = get_axes_limits(clothoidal_paths)
axes = plt.axes(xlim=(x_min, x_max), ylim=(y_min, y_max))
axes.plot(start.x, start.y, 'ro')
axes.plot(goal.x, goal.y, 'ro')
lines = [axes.plot([], [], 'b-')[0] for _ in range(len(clothoidal_paths))]
def animate(i):
for line, clothoid_path in zip(lines, clothoidal_paths):
x = [p.x for p in clothoid_path[:i]]
y = [p.y for p in clothoid_path[:i]]
line.set_data(x, y)
return lines
anim = animation.FuncAnimation(
fig,
animate,
frames=num_steps,
interval=25,
blit=True
)
if save_animation:
anim.save('clothoid.gif', fps=30, writer="imagemagick")
plt.show()
def main():
start_point = Point(0, 0)
start_orientation_list = [0.0]
goal_point = Point(10, 0)
goal_orientation_list = np.linspace(-pi, pi, 75)
num_path_points = 100
clothoid_paths = generate_clothoid_paths(
start_point, start_orientation_list,
goal_point, goal_orientation_list,
num_path_points)
if show_animation:
draw_clothoids(start_point, goal_point,
num_path_points, clothoid_paths,
save_animation=False)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/PathPlanning/ClothoidPath/clothoid_path_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,481 |
```python
"""
Unicycle model class
author Atsushi Sakai
"""
import math
import numpy as np
from utils.angle import angle_mod
dt = 0.05 # [s]
L = 0.9 # [m]
steer_max = np.deg2rad(40.0)
curvature_max = math.tan(steer_max) / L
curvature_max = 1.0 / curvature_max + 1.0
accel_max = 5.0
class State:
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
def update(state, a, delta):
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 / L * math.tan(delta) * dt
state.yaw = pi_2_pi(state.yaw)
state.v = state.v + a * dt
return state
def pi_2_pi(angle):
return angle_mod(angle)
if __name__ == '__main__': # pragma: no cover
print("start unicycle simulation")
import matplotlib.pyplot as plt
T = 100
a = [1.0] * T
delta = [np.deg2rad(1.0)] * T
# print(delta)
# print(a, delta)
state = State()
x = []
y = []
yaw = []
v = []
for (ai, di) in zip(a, delta):
state = update(state, ai, di)
x.append(state.x)
y.append(state.y)
yaw.append(state.yaw)
v.append(state.v)
plt.subplots(1)
plt.plot(x, y)
plt.axis("equal")
plt.grid(True)
plt.subplots(1)
plt.plot(v)
plt.grid(True)
plt.show()
``` | /content/code_sandbox/PathPlanning/ClosedLoopRRTStar/unicycle_model.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 464 |
```python
"""
Path planning Sample Code with Closed loop RRT for car like robot.
author: AtsushiSakai(@Atsushi_twi)
"""
import matplotlib.pyplot as plt
import numpy as np
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from ClosedLoopRRTStar import pure_pursuit
from ClosedLoopRRTStar import unicycle_model
from ReedsSheppPath import reeds_shepp_path_planning
from RRTStarReedsShepp.rrt_star_reeds_shepp import RRTStarReedsShepp
show_animation = True
class ClosedLoopRRTStar(RRTStarReedsShepp):
"""
Class for Closed loop RRT star planning
"""
def __init__(self, start, goal, obstacle_list, rand_area,
max_iter=200,
connect_circle_dist=50.0,
robot_radius=0.0
):
super().__init__(start, goal, obstacle_list, rand_area,
max_iter=max_iter,
connect_circle_dist=connect_circle_dist,
robot_radius=robot_radius
)
self.target_speed = 10.0 / 3.6
self.yaw_th = np.deg2rad(3.0)
self.xy_th = 0.5
self.invalid_travel_ratio = 5.0
def planning(self, animation=True):
"""
do planning
animation: flag for animation on or off
"""
# planning with RRTStarReedsShepp
super().planning(animation=animation)
# generate coruse
path_indexs = self.get_goal_indexes()
flag, x, y, yaw, v, t, a, d = self.search_best_feasible_path(
path_indexs)
return flag, x, y, yaw, v, t, a, d
def search_best_feasible_path(self, path_indexs):
print("Start search feasible path")
best_time = float("inf")
fx, fy, fyaw, fv, ft, fa, fd = None, None, None, None, None, None, None
# pure pursuit tracking
for ind in path_indexs:
path = self.generate_final_course(ind)
flag, x, y, yaw, v, t, a, d = self.check_tracking_path_is_feasible(
path)
if flag and best_time >= t[-1]:
print("feasible path is found")
best_time = t[-1]
fx, fy, fyaw, fv, ft, fa, fd = x, y, yaw, v, t, a, d
print("best time is")
print(best_time)
if fx:
fx.append(self.end.x)
fy.append(self.end.y)
fyaw.append(self.end.yaw)
return True, fx, fy, fyaw, fv, ft, fa, fd
return False, None, None, None, None, None, None, None
def check_tracking_path_is_feasible(self, path):
cx = np.array([state[0] for state in path])[::-1]
cy = np.array([state[1] for state in path])[::-1]
cyaw = np.array([state[2] for state in path])[::-1]
goal = [cx[-1], cy[-1], cyaw[-1]]
cx, cy, cyaw = pure_pursuit.extend_path(cx, cy, cyaw)
speed_profile = pure_pursuit.calc_speed_profile(
cx, cy, cyaw, self.target_speed)
t, x, y, yaw, v, a, d, find_goal = pure_pursuit.closed_loop_prediction(
cx, cy, cyaw, speed_profile, goal)
yaw = [reeds_shepp_path_planning.pi_2_pi(iyaw) for iyaw in yaw]
if not find_goal:
print("cannot reach goal")
if abs(yaw[-1] - goal[2]) >= self.yaw_th * 10.0:
print("final angle is bad")
find_goal = False
travel = unicycle_model.dt * sum(np.abs(v))
origin_travel = sum(np.hypot(np.diff(cx), np.diff(cy)))
if (travel / origin_travel) >= self.invalid_travel_ratio:
print("path is too long")
find_goal = False
tmp_node = self.Node(x, y, 0)
tmp_node.path_x = x
tmp_node.path_y = y
if not self.check_collision(
tmp_node, self.obstacle_list, self.robot_radius):
print("This path is collision")
find_goal = False
return find_goal, x, y, yaw, v, t, a, d
def get_goal_indexes(self):
goalinds = []
for (i, node) in enumerate(self.node_list):
if self.calc_dist_to_goal(node.x, node.y) <= self.xy_th:
goalinds.append(i)
print("OK XY TH num is")
print(len(goalinds))
# angle check
fgoalinds = []
for i in goalinds:
if abs(self.node_list[i].yaw - self.end.yaw) <= self.yaw_th:
fgoalinds.append(i)
print("OK YAW TH num is")
print(len(fgoalinds))
return fgoalinds
def main(gx=6.0, gy=7.0, gyaw=np.deg2rad(90.0), max_iter=100):
print("Start" + __file__)
# ====Search Path with RRT====
obstacle_list = [
(5, 5, 1),
(4, 6, 1),
(4, 8, 1),
(4, 10, 1),
(6, 5, 1),
(7, 5, 1),
(8, 6, 1),
(8, 8, 1),
(8, 10, 1)
] # [x,y,size(radius)]
# Set Initial parameters
start = [0.0, 0.0, np.deg2rad(0.0)]
goal = [gx, gy, gyaw]
closed_loop_rrt_star = ClosedLoopRRTStar(start, goal,
obstacle_list,
[-2.0, 20.0],
max_iter=max_iter)
flag, x, y, yaw, v, t, a, d = closed_loop_rrt_star.planning(
animation=show_animation)
if not flag:
print("cannot find feasible path")
# Draw final path
if show_animation:
closed_loop_rrt_star.draw_graph()
plt.plot(x, y, '-r')
plt.grid(True)
plt.pause(0.001)
plt.subplots(1)
plt.plot(t, [np.rad2deg(iyaw) for iyaw in yaw[:-1]], '-r')
plt.xlabel("time[s]")
plt.ylabel("Yaw[deg]")
plt.grid(True)
plt.subplots(1)
plt.plot(t, [iv * 3.6 for iv in v], '-r')
plt.xlabel("time[s]")
plt.ylabel("velocity[km/h]")
plt.grid(True)
plt.subplots(1)
plt.plot(t, a, '-r')
plt.xlabel("time[s]")
plt.ylabel("accel[m/ss]")
plt.grid(True)
plt.subplots(1)
plt.plot(t, [np.rad2deg(td) for td in d], '-r')
plt.xlabel("time[s]")
plt.ylabel("Steering angle[deg]")
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/ClosedLoopRRTStar/closed_loop_rrt_star_car.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,681 |
```python
"""
Path tracking simulation with pure pursuit steering control and PID speed control.
author: Atsushi Sakai
"""
import math
import matplotlib.pyplot as plt
import numpy as np
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from ClosedLoopRRTStar import unicycle_model
Kp = 2.0 # speed propotional gain
Lf = 0.5 # look-ahead distance
T = 100.0 # max simulation time
goal_dis = 0.5
stop_speed = 0.5
# animation = True
animation = False
def PIDControl(target, current):
a = Kp * (target - current)
if a > unicycle_model.accel_max:
a = unicycle_model.accel_max
elif a < -unicycle_model.accel_max:
a = -unicycle_model.accel_max
return a
def pure_pursuit_control(state, cx, cy, pind):
ind, dis = calc_target_index(state, cx, cy)
if pind >= ind:
ind = pind
# print(parent_index, ind)
if ind < len(cx):
tx = cx[ind]
ty = cy[ind]
else:
tx = cx[-1]
ty = cy[-1]
ind = len(cx) - 1
alpha = math.atan2(ty - state.y, tx - state.x) - state.yaw
if state.v <= 0.0: # back
alpha = math.pi - alpha
delta = math.atan2(2.0 * unicycle_model.L * math.sin(alpha) / Lf, 1.0)
if delta > unicycle_model.steer_max:
delta = unicycle_model.steer_max
elif delta < - unicycle_model.steer_max:
delta = -unicycle_model.steer_max
return delta, ind, dis
def calc_target_index(state, cx, cy):
dx = [state.x - icx for icx in cx]
dy = [state.y - icy for icy in cy]
d = np.hypot(dx, dy)
mindis = min(d)
ind = np.argmin(d)
L = 0.0
while Lf > L and (ind + 1) < len(cx):
dx = cx[ind + 1] - cx[ind]
dy = cy[ind + 1] - cy[ind]
L += math.hypot(dx, dy)
ind += 1
# print(mindis)
return ind, mindis
def closed_loop_prediction(cx, cy, cyaw, speed_profile, goal):
state = unicycle_model.State(x=-0.0, y=-0.0, yaw=0.0, v=0.0)
# lastIndex = len(cx) - 1
time = 0.0
x = [state.x]
y = [state.y]
yaw = [state.yaw]
v = [state.v]
t = [0.0]
a = [0.0]
d = [0.0]
target_ind, mindis = calc_target_index(state, cx, cy)
find_goal = False
maxdis = 0.5
while T >= time:
di, target_ind, dis = pure_pursuit_control(state, cx, cy, target_ind)
target_speed = speed_profile[target_ind]
target_speed = target_speed * \
(maxdis - min(dis, maxdis - 0.1)) / maxdis
ai = PIDControl(target_speed, state.v)
state = unicycle_model.update(state, ai, di)
if abs(state.v) <= stop_speed and target_ind <= len(cx) - 2:
target_ind += 1
time = time + unicycle_model.dt
# check goal
dx = state.x - goal[0]
dy = state.y - goal[1]
if math.hypot(dx, dy) <= goal_dis:
find_goal = True
break
x.append(state.x)
y.append(state.y)
yaw.append(state.yaw)
v.append(state.v)
t.append(time)
a.append(ai)
d.append(di)
if target_ind % 1 == 0 and 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, "ob", label="trajectory")
plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
plt.axis("equal")
plt.grid(True)
plt.title("speed:" + str(round(state.v, 2))
+ "tind:" + str(target_ind))
plt.pause(0.0001)
else:
print("Time out!!")
return t, x, y, yaw, v, a, d, find_goal
def set_stop_point(target_speed, cx, cy, cyaw):
speed_profile = [target_speed] * len(cx)
forward = True
d = []
is_back = False
# Set stop point
for i in range(len(cx) - 1):
dx = cx[i + 1] - cx[i]
dy = cy[i + 1] - cy[i]
d.append(math.hypot(dx, dy))
iyaw = cyaw[i]
move_direction = math.atan2(dy, dx)
is_back = abs(move_direction - iyaw) >= math.pi / 2.0
if dx == 0.0 and dy == 0.0:
continue
if is_back:
speed_profile[i] = - target_speed
else:
speed_profile[i] = target_speed
if is_back and forward:
speed_profile[i] = 0.0
forward = False
# plt.plot(cx[i], cy[i], "xb")
# print(i_yaw, move_direction, dx, dy)
elif not is_back and not forward:
speed_profile[i] = 0.0
forward = True
# plt.plot(cx[i], cy[i], "xb")
# print(i_yaw, move_direction, dx, dy)
speed_profile[0] = 0.0
if is_back:
speed_profile[-1] = -stop_speed
else:
speed_profile[-1] = stop_speed
d.append(d[-1])
return speed_profile, d
def calc_speed_profile(cx, cy, cyaw, target_speed):
speed_profile, d = set_stop_point(target_speed, cx, cy, cyaw)
if animation: # pragma: no cover
plt.plot(speed_profile, "xb")
return speed_profile
def extend_path(cx, cy, cyaw):
dl = 0.1
dl_list = [dl] * (int(Lf / dl) + 1)
move_direction = math.atan2(cy[-1] - cy[-3], cx[-1] - cx[-3])
is_back = abs(move_direction - cyaw[-1]) >= math.pi / 2.0
for idl in dl_list:
if is_back:
idl *= -1
cx = np.append(cx, cx[-1] + idl * math.cos(cyaw[-1]))
cy = np.append(cy, cy[-1] + idl * math.sin(cyaw[-1]))
cyaw = np.append(cyaw, cyaw[-1])
return cx, cy, cyaw
def main(): # pragma: no cover
# target course
cx = np.arange(0, 50, 0.1)
cy = [math.sin(ix / 5.0) * ix / 2.0 for ix in cx]
target_speed = 5.0 / 3.6
T = 15.0 # max simulation time
state = unicycle_model.State(x=-0.0, y=-3.0, yaw=0.0, v=0.0)
# state = unicycle_model.State(x=-1.0, y=-5.0, yaw=0.0, v=-30.0 / 3.6)
# state = unicycle_model.State(x=10.0, y=5.0, yaw=0.0, v=-30.0 / 3.6)
# state = unicycle_model.State(
# x=3.0, y=5.0, yaw=np.deg2rad(-40.0), v=-10.0 / 3.6)
# state = unicycle_model.State(
# x=3.0, y=5.0, yaw=np.deg2rad(40.0), v=50.0 / 3.6)
lastIndex = len(cx) - 1
time = 0.0
x = [state.x]
y = [state.y]
yaw = [state.yaw]
v = [state.v]
t = [0.0]
target_ind, dis = calc_target_index(state, cx, cy)
while T >= time and lastIndex > target_ind:
ai = PIDControl(target_speed, state.v)
di, target_ind, _ = pure_pursuit_control(state, cx, cy, target_ind)
state = unicycle_model.update(state, ai, di)
time = time + unicycle_model.dt
x.append(state.x)
y.append(state.y)
yaw.append(state.yaw)
v.append(state.v)
t.append(time)
# plt.cla()
# plt.plot(cx, cy, ".r", label="course")
# plt.plot(x, y, "-b", label="trajectory")
# plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
# plt.axis("equal")
# plt.grid(True)
# plt.pause(0.1)
# input()
plt.subplots(1)
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()
if __name__ == '__main__': # pragma: no cover
print("Pure pursuit path tracking simulation start")
main()
``` | /content/code_sandbox/PathPlanning/ClosedLoopRRTStar/pure_pursuit.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,372 |
```python
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
``` | /content/code_sandbox/PathPlanning/HybridAStar/__init__.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 20 |
```python
"""
Bidirectional A* grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class BidirectionalAStarPlanner:
def __init__(self, ox, oy, resolution, rr):
"""
Initialize grid map for a star planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.min_x, self.min_y = None, None
self.max_x, self.max_y = None, None
self.x_width, self.y_width, self.obstacle_map = None, None, None
self.resolution = resolution
self.rr = rr
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
Bidirectional A star path search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1)
open_set_A, closed_set_A = dict(), dict()
open_set_B, closed_set_B = dict(), dict()
open_set_A[self.calc_grid_index(start_node)] = start_node
open_set_B[self.calc_grid_index(goal_node)] = goal_node
current_A = start_node
current_B = goal_node
meet_point_A, meet_point_B = None, None
while True:
if len(open_set_A) == 0:
print("Open set A is empty..")
break
if len(open_set_B) == 0:
print("Open set B is empty..")
break
c_id_A = min(
open_set_A,
key=lambda o: self.find_total_cost(open_set_A, o, current_B))
current_A = open_set_A[c_id_A]
c_id_B = min(
open_set_B,
key=lambda o: self.find_total_cost(open_set_B, o, current_A))
current_B = open_set_B[c_id_B]
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current_A.x, self.min_x),
self.calc_grid_position(current_A.y, self.min_y),
"xc")
plt.plot(self.calc_grid_position(current_B.x, self.min_x),
self.calc_grid_position(current_B.y, self.min_y),
"xc")
# 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 len(closed_set_A.keys()) % 10 == 0:
plt.pause(0.001)
if current_A.x == current_B.x and current_A.y == current_B.y:
print("Found goal")
meet_point_A = current_A
meet_point_B = current_B
break
# Remove the item from the open set
del open_set_A[c_id_A]
del open_set_B[c_id_B]
# Add it to the closed set
closed_set_A[c_id_A] = current_A
closed_set_B[c_id_B] = current_B
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
c_nodes = [self.Node(current_A.x + self.motion[i][0],
current_A.y + self.motion[i][1],
current_A.cost + self.motion[i][2],
c_id_A),
self.Node(current_B.x + self.motion[i][0],
current_B.y + self.motion[i][1],
current_B.cost + self.motion[i][2],
c_id_B)]
n_ids = [self.calc_grid_index(c_nodes[0]),
self.calc_grid_index(c_nodes[1])]
# If the node is not safe, do nothing
continue_ = self.check_nodes_and_sets(c_nodes, closed_set_A,
closed_set_B, n_ids)
if not continue_[0]:
if n_ids[0] not in open_set_A:
# discovered a new node
open_set_A[n_ids[0]] = c_nodes[0]
else:
if open_set_A[n_ids[0]].cost > c_nodes[0].cost:
# This path is the best until now. record it
open_set_A[n_ids[0]] = c_nodes[0]
if not continue_[1]:
if n_ids[1] not in open_set_B:
# discovered a new node
open_set_B[n_ids[1]] = c_nodes[1]
else:
if open_set_B[n_ids[1]].cost > c_nodes[1].cost:
# This path is the best until now. record it
open_set_B[n_ids[1]] = c_nodes[1]
rx, ry = self.calc_final_bidirectional_path(
meet_point_A, meet_point_B, closed_set_A, closed_set_B)
return rx, ry
# takes two sets and two meeting nodes and return the optimal path
def calc_final_bidirectional_path(self, n1, n2, setA, setB):
rx_A, ry_A = self.calc_final_path(n1, setA)
rx_B, ry_B = self.calc_final_path(n2, setB)
rx_A.reverse()
ry_A.reverse()
rx = rx_A + rx_B
ry = ry_A + ry_B
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], \
[self.calc_grid_position(goal_node.y, self.min_y)]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(self.calc_grid_position(n.x, self.min_x))
ry.append(self.calc_grid_position(n.y, self.min_y))
parent_index = n.parent_index
return rx, ry
def check_nodes_and_sets(self, c_nodes, closedSet_A, closedSet_B, n_ids):
continue_ = [False, False]
if not self.verify_node(c_nodes[0]) or n_ids[0] in closedSet_A:
continue_[0] = True
if not self.verify_node(c_nodes[1]) or n_ids[1] in closedSet_B:
continue_[1] = True
return continue_
@staticmethod
def calc_heuristic(n1, n2):
w = 1.0 # weight of heuristic
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
return d
def find_total_cost(self, open_set, lambda_, n1):
g_cost = open_set[lambda_].cost
h_cost = self.calc_heuristic(n1, open_set[lambda_])
f_cost = g_cost + h_cost
return f_cost
def calc_grid_position(self, index, min_position):
"""
calc grid position
:param index:
:param min_position:
:return:
"""
pos = index * self.resolution + min_position
return pos
def calc_xy_index(self, position, min_pos):
return round((position - min_pos) / self.resolution)
def calc_grid_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.min_x)
py = self.calc_grid_position(node.y, self.min_y)
if px < self.min_x:
return False
elif py < self.min_y:
return False
elif px >= self.max_x:
return False
elif py >= self.max_y:
return False
# collision check
if self.obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
# obstacle map generation
self.obstacle_map = [[False for _ in range(self.y_width)]
for _ in range(self.x_width)]
for ix in range(self.x_width):
x = self.calc_grid_position(ix, self.min_x)
for iy in range(self.y_width):
y = self.calc_grid_position(iy, self.min_y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obstacle_map[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "ob")
plt.grid(True)
plt.axis("equal")
bidir_a_star = BidirectionalAStarPlanner(ox, oy, grid_size, robot_radius)
rx, ry = bidir_a_star.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(.0001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/BidirectionalAStar/bidirectional_a_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,756 |
```python
"""
Hybrid A* path planning
author: Zheng Zh (@Zhengzh)
"""
import heapq
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import cKDTree
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from dynamic_programming_heuristic import calc_distance_heuristic
from ReedsSheppPath import reeds_shepp_path_planning as rs
from car import move, check_car_collision, MAX_STEER, WB, plot_car, BUBBLE_R
XY_GRID_RESOLUTION = 2.0 # [m]
YAW_GRID_RESOLUTION = np.deg2rad(15.0) # [rad]
MOTION_RESOLUTION = 0.1 # [m] path interpolate resolution
N_STEER = 20 # number of steer command
SB_COST = 100.0 # switch back penalty cost
BACK_COST = 5.0 # backward penalty cost
STEER_CHANGE_COST = 5.0 # steer angle change penalty cost
STEER_COST = 1.0 # steer angle change penalty cost
H_COST = 5.0 # Heuristic cost
show_animation = True
class Node:
def __init__(self, x_ind, y_ind, yaw_ind, direction,
x_list, y_list, yaw_list, directions,
steer=0.0, parent_index=None, cost=None):
self.x_index = x_ind
self.y_index = y_ind
self.yaw_index = yaw_ind
self.direction = direction
self.x_list = x_list
self.y_list = y_list
self.yaw_list = yaw_list
self.directions = directions
self.steer = steer
self.parent_index = parent_index
self.cost = cost
class Path:
def __init__(self, x_list, y_list, yaw_list, direction_list, cost):
self.x_list = x_list
self.y_list = y_list
self.yaw_list = yaw_list
self.direction_list = direction_list
self.cost = cost
class Config:
def __init__(self, ox, oy, xy_resolution, yaw_resolution):
min_x_m = min(ox)
min_y_m = min(oy)
max_x_m = max(ox)
max_y_m = max(oy)
ox.append(min_x_m)
oy.append(min_y_m)
ox.append(max_x_m)
oy.append(max_y_m)
self.min_x = round(min_x_m / xy_resolution)
self.min_y = round(min_y_m / xy_resolution)
self.max_x = round(max_x_m / xy_resolution)
self.max_y = round(max_y_m / xy_resolution)
self.x_w = round(self.max_x - self.min_x)
self.y_w = round(self.max_y - self.min_y)
self.min_yaw = round(- math.pi / yaw_resolution) - 1
self.max_yaw = round(math.pi / yaw_resolution)
self.yaw_w = round(self.max_yaw - self.min_yaw)
def calc_motion_inputs():
for steer in np.concatenate((np.linspace(-MAX_STEER, MAX_STEER,
N_STEER), [0.0])):
for d in [1, -1]:
yield [steer, d]
def get_neighbors(current, config, ox, oy, kd_tree):
for steer, d in calc_motion_inputs():
node = calc_next_node(current, steer, d, config, ox, oy, kd_tree)
if node and verify_index(node, config):
yield node
def calc_next_node(current, steer, direction, config, ox, oy, kd_tree):
x, y, yaw = current.x_list[-1], current.y_list[-1], current.yaw_list[-1]
arc_l = XY_GRID_RESOLUTION * 1.5
x_list, y_list, yaw_list = [], [], []
for _ in np.arange(0, arc_l, MOTION_RESOLUTION):
x, y, yaw = move(x, y, yaw, MOTION_RESOLUTION * direction, steer)
x_list.append(x)
y_list.append(y)
yaw_list.append(yaw)
if not check_car_collision(x_list, y_list, yaw_list, ox, oy, kd_tree):
return None
d = direction == 1
x_ind = round(x / XY_GRID_RESOLUTION)
y_ind = round(y / XY_GRID_RESOLUTION)
yaw_ind = round(yaw / YAW_GRID_RESOLUTION)
added_cost = 0.0
if d != current.direction:
added_cost += SB_COST
# steer penalty
added_cost += STEER_COST * abs(steer)
# steer change penalty
added_cost += STEER_CHANGE_COST * abs(current.steer - steer)
cost = current.cost + added_cost + arc_l
node = Node(x_ind, y_ind, yaw_ind, d, x_list,
y_list, yaw_list, [d],
parent_index=calc_index(current, config),
cost=cost, steer=steer)
return node
def is_same_grid(n1, n2):
if n1.x_index == n2.x_index \
and n1.y_index == n2.y_index \
and n1.yaw_index == n2.yaw_index:
return True
return False
def analytic_expansion(current, goal, ox, oy, kd_tree):
start_x = current.x_list[-1]
start_y = current.y_list[-1]
start_yaw = current.yaw_list[-1]
goal_x = goal.x_list[-1]
goal_y = goal.y_list[-1]
goal_yaw = goal.yaw_list[-1]
max_curvature = math.tan(MAX_STEER) / WB
paths = rs.calc_paths(start_x, start_y, start_yaw,
goal_x, goal_y, goal_yaw,
max_curvature, step_size=MOTION_RESOLUTION)
if not paths:
return None
best_path, best = None, None
for path in paths:
if check_car_collision(path.x, path.y, path.yaw, ox, oy, kd_tree):
cost = calc_rs_path_cost(path)
if not best or best > cost:
best = cost
best_path = path
return best_path
def update_node_with_analytic_expansion(current, goal,
c, ox, oy, kd_tree):
path = analytic_expansion(current, goal, ox, oy, kd_tree)
if path:
if show_animation:
plt.plot(path.x, path.y)
f_x = path.x[1:]
f_y = path.y[1:]
f_yaw = path.yaw[1:]
f_cost = current.cost + calc_rs_path_cost(path)
f_parent_index = calc_index(current, c)
fd = []
for d in path.directions[1:]:
fd.append(d >= 0)
f_steer = 0.0
f_path = Node(current.x_index, current.y_index, current.yaw_index,
current.direction, f_x, f_y, f_yaw, fd,
cost=f_cost, parent_index=f_parent_index, steer=f_steer)
return True, f_path
return False, None
def calc_rs_path_cost(reed_shepp_path):
cost = 0.0
for length in reed_shepp_path.lengths:
if length >= 0: # forward
cost += length
else: # back
cost += abs(length) * BACK_COST
# switch back penalty
for i in range(len(reed_shepp_path.lengths) - 1):
# switch back
if reed_shepp_path.lengths[i] * reed_shepp_path.lengths[i + 1] < 0.0:
cost += SB_COST
# steer penalty
for course_type in reed_shepp_path.ctypes:
if course_type != "S": # curve
cost += STEER_COST * abs(MAX_STEER)
# ==steer change penalty
# calc steer profile
n_ctypes = len(reed_shepp_path.ctypes)
u_list = [0.0] * n_ctypes
for i in range(n_ctypes):
if reed_shepp_path.ctypes[i] == "R":
u_list[i] = - MAX_STEER
elif reed_shepp_path.ctypes[i] == "L":
u_list[i] = MAX_STEER
for i in range(len(reed_shepp_path.ctypes) - 1):
cost += STEER_CHANGE_COST * abs(u_list[i + 1] - u_list[i])
return cost
def hybrid_a_star_planning(start, goal, ox, oy, xy_resolution, yaw_resolution):
"""
start: start node
goal: goal node
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
xy_resolution: grid resolution [m]
yaw_resolution: yaw angle resolution [rad]
"""
start[2], goal[2] = rs.pi_2_pi(start[2]), rs.pi_2_pi(goal[2])
tox, toy = ox[:], oy[:]
obstacle_kd_tree = cKDTree(np.vstack((tox, toy)).T)
config = Config(tox, toy, xy_resolution, yaw_resolution)
start_node = Node(round(start[0] / xy_resolution),
round(start[1] / xy_resolution),
round(start[2] / yaw_resolution), True,
[start[0]], [start[1]], [start[2]], [True], cost=0)
goal_node = Node(round(goal[0] / xy_resolution),
round(goal[1] / xy_resolution),
round(goal[2] / yaw_resolution), True,
[goal[0]], [goal[1]], [goal[2]], [True])
openList, closedList = {}, {}
h_dp = calc_distance_heuristic(
goal_node.x_list[-1], goal_node.y_list[-1],
ox, oy, xy_resolution, BUBBLE_R)
pq = []
openList[calc_index(start_node, config)] = start_node
heapq.heappush(pq, (calc_cost(start_node, h_dp, config),
calc_index(start_node, config)))
final_path = None
while True:
if not openList:
print("Error: Cannot find path, No open set")
return [], [], []
cost, c_id = heapq.heappop(pq)
if c_id in openList:
current = openList.pop(c_id)
closedList[c_id] = current
else:
continue
if show_animation: # pragma: no cover
plt.plot(current.x_list[-1], current.y_list[-1], "xc")
# 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 len(closedList.keys()) % 10 == 0:
plt.pause(0.001)
is_updated, final_path = update_node_with_analytic_expansion(
current, goal_node, config, ox, oy, obstacle_kd_tree)
if is_updated:
print("path found")
break
for neighbor in get_neighbors(current, config, ox, oy,
obstacle_kd_tree):
neighbor_index = calc_index(neighbor, config)
if neighbor_index in closedList:
continue
if neighbor_index not in openList \
or openList[neighbor_index].cost > neighbor.cost:
heapq.heappush(
pq, (calc_cost(neighbor, h_dp, config),
neighbor_index))
openList[neighbor_index] = neighbor
path = get_final_path(closedList, final_path)
return path
def calc_cost(n, h_dp, c):
ind = (n.y_index - c.min_y) * c.x_w + (n.x_index - c.min_x)
if ind not in h_dp:
return n.cost + 999999999 # collision cost
return n.cost + H_COST * h_dp[ind].cost
def get_final_path(closed, goal_node):
reversed_x, reversed_y, reversed_yaw = \
list(reversed(goal_node.x_list)), list(reversed(goal_node.y_list)), \
list(reversed(goal_node.yaw_list))
direction = list(reversed(goal_node.directions))
nid = goal_node.parent_index
final_cost = goal_node.cost
while nid:
n = closed[nid]
reversed_x.extend(list(reversed(n.x_list)))
reversed_y.extend(list(reversed(n.y_list)))
reversed_yaw.extend(list(reversed(n.yaw_list)))
direction.extend(list(reversed(n.directions)))
nid = n.parent_index
reversed_x = list(reversed(reversed_x))
reversed_y = list(reversed(reversed_y))
reversed_yaw = list(reversed(reversed_yaw))
direction = list(reversed(direction))
# adjust first direction
direction[0] = direction[1]
path = Path(reversed_x, reversed_y, reversed_yaw, direction, final_cost)
return path
def verify_index(node, c):
x_ind, y_ind = node.x_index, node.y_index
if c.min_x <= x_ind <= c.max_x and c.min_y <= y_ind <= c.max_y:
return True
return False
def calc_index(node, c):
ind = (node.yaw_index - c.min_yaw) * c.x_w * c.y_w + \
(node.y_index - c.min_y) * c.x_w + (node.x_index - c.min_x)
if ind <= 0:
print("Error(calc_index):", ind)
return ind
def main():
print("Start Hybrid A* planning")
ox, oy = [], []
for i in range(60):
ox.append(i)
oy.append(0.0)
for i in range(60):
ox.append(60.0)
oy.append(i)
for i in range(61):
ox.append(i)
oy.append(60.0)
for i in range(61):
ox.append(0.0)
oy.append(i)
for i in range(40):
ox.append(20.0)
oy.append(i)
for i in range(40):
ox.append(40.0)
oy.append(60.0 - i)
# Set Initial parameters
start = [10.0, 10.0, np.deg2rad(90.0)]
goal = [50.0, 50.0, np.deg2rad(-90.0)]
print("start : ", start)
print("goal : ", goal)
if show_animation:
plt.plot(ox, oy, ".k")
rs.plot_arrow(start[0], start[1], start[2], fc='g')
rs.plot_arrow(goal[0], goal[1], goal[2])
plt.grid(True)
plt.axis("equal")
path = hybrid_a_star_planning(
start, goal, ox, oy, XY_GRID_RESOLUTION, YAW_GRID_RESOLUTION)
x = path.x_list
y = path.y_list
yaw = path.yaw_list
if show_animation:
for i_x, i_y, i_yaw in zip(x, y, yaw):
plt.cla()
plt.plot(ox, oy, ".k")
plt.plot(x, y, "-r", label="Hybrid A* path")
plt.grid(True)
plt.axis("equal")
plot_car(i_x, i_y, i_yaw)
plt.pause(0.0001)
print(__file__ + " done!!")
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/HybridAStar/hybrid_a_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,450 |
```python
"""
A* grid based planning
author: Nikos Kanargias (nkana@tee.gr)
See Wikipedia article (path_to_url
"""
import heapq
import math
import matplotlib.pyplot as plt
show_animation = False
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x
self.y = y
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def calc_final_path(goal_node, closed_node_set, resolution):
# generate final course
rx, ry = [goal_node.x * resolution], [goal_node.y * resolution]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_node_set[parent_index]
rx.append(n.x * resolution)
ry.append(n.y * resolution)
parent_index = n.parent_index
return rx, ry
def calc_distance_heuristic(gx, gy, ox, oy, resolution, rr):
"""
gx: goal x position [m]
gx: goal x position [m]
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
goal_node = Node(round(gx / resolution), round(gy / resolution), 0.0, -1)
ox = [iox / resolution for iox in ox]
oy = [ioy / resolution for ioy in oy]
obstacle_map, min_x, min_y, max_x, max_y, x_w, y_w = calc_obstacle_map(
ox, oy, resolution, rr)
motion = get_motion_model()
open_set, closed_set = dict(), dict()
open_set[calc_index(goal_node, x_w, min_x, min_y)] = goal_node
priority_queue = [(0, calc_index(goal_node, x_w, min_x, min_y))]
while True:
if not priority_queue:
break
cost, c_id = heapq.heappop(priority_queue)
if c_id in open_set:
current = open_set[c_id]
closed_set[c_id] = current
open_set.pop(c_id)
else:
continue
# show graph
if show_animation: # pragma: no cover
plt.plot(current.x * resolution, current.y * resolution, "xc")
# 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 len(closed_set.keys()) % 10 == 0:
plt.pause(0.001)
# Remove the item from the open set
# expand search grid based on motion model
for i, _ in enumerate(motion):
node = Node(current.x + motion[i][0],
current.y + motion[i][1],
current.cost + motion[i][2], c_id)
n_id = calc_index(node, x_w, min_x, min_y)
if n_id in closed_set:
continue
if not verify_node(node, obstacle_map, min_x, min_y, max_x, max_y):
continue
if n_id not in open_set:
open_set[n_id] = node # Discover a new node
heapq.heappush(
priority_queue,
(node.cost, calc_index(node, x_w, min_x, min_y)))
else:
if open_set[n_id].cost >= node.cost:
# This path is the best until now. record it!
open_set[n_id] = node
heapq.heappush(
priority_queue,
(node.cost, calc_index(node, x_w, min_x, min_y)))
return closed_set
def verify_node(node, obstacle_map, min_x, min_y, max_x, max_y):
if node.x < min_x:
return False
elif node.y < min_y:
return False
elif node.x >= max_x:
return False
elif node.y >= max_y:
return False
if obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(ox, oy, resolution, vr):
min_x = round(min(ox))
min_y = round(min(oy))
max_x = round(max(ox))
max_y = round(max(oy))
x_width = round(max_x - min_x)
y_width = round(max_y - min_y)
# obstacle map generation
obstacle_map = [[False for _ in range(y_width)] for _ in range(x_width)]
for ix in range(x_width):
x = ix + min_x
for iy in range(y_width):
y = iy + min_y
# print(x, y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= vr / resolution:
obstacle_map[ix][iy] = True
break
return obstacle_map, min_x, min_y, max_x, max_y, x_width, y_width
def calc_index(node, x_width, x_min, y_min):
return (node.y - y_min) * x_width + (node.x - x_min)
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
``` | /content/code_sandbox/PathPlanning/HybridAStar/dynamic_programming_heuristic.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,297 |
```python
"""
Car model for Hybrid A* path planning
author: Zheng Zh (@Zhengzh)
"""
import sys
import pathlib
root_dir = pathlib.Path(__file__).parent.parent.parent
sys.path.append(str(root_dir))
from math import cos, sin, tan, pi
import matplotlib.pyplot as plt
import numpy as np
from utils.angle import rot_mat_2d
WB = 3.0 # rear to front wheel
W = 2.0 # width of car
LF = 3.3 # distance from rear to vehicle front end
LB = 1.0 # distance from rear to vehicle back end
MAX_STEER = 0.6 # [rad] maximum steering angle
BUBBLE_DIST = (LF - LB) / 2.0 # distance from rear to center of vehicle.
BUBBLE_R = np.hypot((LF + LB) / 2.0, W / 2.0) # bubble radius
# vehicle rectangle vertices
VRX = [LF, LF, -LB, -LB, LF]
VRY = [W / 2, -W / 2, -W / 2, W / 2, W / 2]
def check_car_collision(x_list, y_list, yaw_list, ox, oy, kd_tree):
for i_x, i_y, i_yaw in zip(x_list, y_list, yaw_list):
cx = i_x + BUBBLE_DIST * cos(i_yaw)
cy = i_y + BUBBLE_DIST * sin(i_yaw)
ids = kd_tree.query_ball_point([cx, cy], BUBBLE_R)
if not ids:
continue
if not rectangle_check(i_x, i_y, i_yaw,
[ox[i] for i in ids], [oy[i] for i in ids]):
return False # collision
return True # no collision
def rectangle_check(x, y, yaw, ox, oy):
# transform obstacles to base link frame
rot = rot_mat_2d(yaw)
for iox, ioy in zip(ox, oy):
tx = iox - x
ty = ioy - y
converted_xy = np.stack([tx, ty]).T @ rot
rx, ry = converted_xy[0], converted_xy[1]
if not (rx > LF or rx < -LB or ry > W / 2.0 or ry < -W / 2.0):
return False # collision
return True # no collision
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
"""Plot arrow."""
if not isinstance(x, float):
for (i_x, i_y, i_yaw) in zip(x, y, yaw):
plot_arrow(i_x, i_y, i_yaw)
else:
plt.arrow(x, y, length * cos(yaw), length * sin(yaw),
fc=fc, ec=ec, head_width=width, head_length=width, alpha=0.4)
def plot_car(x, y, yaw):
car_color = '-k'
c, s = cos(yaw), sin(yaw)
rot = rot_mat_2d(-yaw)
car_outline_x, car_outline_y = [], []
for rx, ry in zip(VRX, VRY):
converted_xy = np.stack([rx, ry]).T @ rot
car_outline_x.append(converted_xy[0]+x)
car_outline_y.append(converted_xy[1]+y)
arrow_x, arrow_y, arrow_yaw = c * 1.5 + x, s * 1.5 + y, yaw
plot_arrow(arrow_x, arrow_y, arrow_yaw)
plt.plot(car_outline_x, car_outline_y, car_color)
def pi_2_pi(angle):
return (angle + pi) % (2 * pi) - pi
def move(x, y, yaw, distance, steer, L=WB):
x += distance * cos(yaw)
y += distance * sin(yaw)
yaw += pi_2_pi(distance * tan(steer) / L) # distance/2
return x, y, yaw
def main():
x, y, yaw = 0., 0., 1.
plt.axis('equal')
plot_car(x, y, yaw)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/HybridAStar/car.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 967 |
```python
"""
Bug Planning
author: Sarim Mehdi(muhammadsarim.mehdi@studio.unibo.it)
Source: path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
show_animation = True
class BugPlanner:
def __init__(self, start_x, start_y, goal_x, goal_y, obs_x, obs_y):
self.goal_x = goal_x
self.goal_y = goal_y
self.obs_x = obs_x
self.obs_y = obs_y
self.r_x = [start_x]
self.r_y = [start_y]
self.out_x = []
self.out_y = []
for o_x, o_y in zip(obs_x, obs_y):
for add_x, add_y in zip([1, 0, -1, -1, -1, 0, 1, 1],
[1, 1, 1, 0, -1, -1, -1, 0]):
cand_x, cand_y = o_x+add_x, o_y+add_y
valid_point = True
for _x, _y in zip(obs_x, obs_y):
if cand_x == _x and cand_y == _y:
valid_point = False
break
if valid_point:
self.out_x.append(cand_x), self.out_y.append(cand_y)
def mov_normal(self):
return self.r_x[-1] + np.sign(self.goal_x - self.r_x[-1]), \
self.r_y[-1] + np.sign(self.goal_y - self.r_y[-1])
def mov_to_next_obs(self, visited_x, visited_y):
for add_x, add_y in zip([1, 0, -1, 0], [0, 1, 0, -1]):
c_x, c_y = self.r_x[-1] + add_x, self.r_y[-1] + add_y
for _x, _y in zip(self.out_x, self.out_y):
use_pt = True
if c_x == _x and c_y == _y:
for v_x, v_y in zip(visited_x, visited_y):
if c_x == v_x and c_y == v_y:
use_pt = False
break
if use_pt:
return c_x, c_y, False
if not use_pt:
break
return self.r_x[-1], self.r_y[-1], True
def bug0(self):
"""
Greedy algorithm where you move towards goal
until you hit an obstacle. Then you go around it
(pick an arbitrary direction), until it is possible
for you to start moving towards goal in a greedy manner again
"""
mov_dir = 'normal'
cand_x, cand_y = -np.inf, -np.inf
if show_animation:
plt.plot(self.obs_x, self.obs_y, ".k")
plt.plot(self.r_x[-1], self.r_y[-1], "og")
plt.plot(self.goal_x, self.goal_y, "xb")
plt.plot(self.out_x, self.out_y, ".")
plt.grid(True)
plt.title('BUG 0')
for x_ob, y_ob in zip(self.out_x, self.out_y):
if self.r_x[-1] == x_ob and self.r_y[-1] == y_ob:
mov_dir = 'obs'
break
visited_x, visited_y = [], []
while True:
if self.r_x[-1] == self.goal_x and \
self.r_y[-1] == self.goal_y:
break
if mov_dir == 'normal':
cand_x, cand_y = self.mov_normal()
if mov_dir == 'obs':
cand_x, cand_y, _ = self.mov_to_next_obs(visited_x, visited_y)
if mov_dir == 'normal':
found_boundary = False
for x_ob, y_ob in zip(self.out_x, self.out_y):
if cand_x == x_ob and cand_y == y_ob:
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x[:], visited_y[:] = [], []
visited_x.append(cand_x), visited_y.append(cand_y)
mov_dir = 'obs'
found_boundary = True
break
if not found_boundary:
self.r_x.append(cand_x), self.r_y.append(cand_y)
elif mov_dir == 'obs':
can_go_normal = True
for x_ob, y_ob in zip(self.obs_x, self.obs_y):
if self.mov_normal()[0] == x_ob and \
self.mov_normal()[1] == y_ob:
can_go_normal = False
break
if can_go_normal:
mov_dir = 'normal'
else:
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x.append(cand_x), visited_y.append(cand_y)
if show_animation:
plt.plot(self.r_x, self.r_y, "-r")
plt.pause(0.001)
if show_animation:
plt.show()
def bug1(self):
"""
Move towards goal in a greedy manner.
When you hit an obstacle, you go around it and
back to where you hit the obstacle initially.
Then, you go to the point on the obstacle that is
closest to your goal and you start moving towards
goal in a greedy manner from that new point.
"""
mov_dir = 'normal'
cand_x, cand_y = -np.inf, -np.inf
exit_x, exit_y = -np.inf, -np.inf
dist = np.inf
back_to_start = False
second_round = False
if show_animation:
plt.plot(self.obs_x, self.obs_y, ".k")
plt.plot(self.r_x[-1], self.r_y[-1], "og")
plt.plot(self.goal_x, self.goal_y, "xb")
plt.plot(self.out_x, self.out_y, ".")
plt.grid(True)
plt.title('BUG 1')
for xob, yob in zip(self.out_x, self.out_y):
if self.r_x[-1] == xob and self.r_y[-1] == yob:
mov_dir = 'obs'
break
visited_x, visited_y = [], []
while True:
if self.r_x[-1] == self.goal_x and \
self.r_y[-1] == self.goal_y:
break
if mov_dir == 'normal':
cand_x, cand_y = self.mov_normal()
if mov_dir == 'obs':
cand_x, cand_y, back_to_start = \
self.mov_to_next_obs(visited_x, visited_y)
if mov_dir == 'normal':
found_boundary = False
for x_ob, y_ob in zip(self.out_x, self.out_y):
if cand_x == x_ob and cand_y == y_ob:
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x[:], visited_y[:] = [], []
visited_x.append(cand_x), visited_y.append(cand_y)
mov_dir = 'obs'
dist = np.inf
back_to_start = False
second_round = False
found_boundary = True
break
if not found_boundary:
self.r_x.append(cand_x), self.r_y.append(cand_y)
elif mov_dir == 'obs':
d = np.linalg.norm(np.array([cand_x, cand_y] -
np.array([self.goal_x,
self.goal_y])))
if d < dist and not second_round:
exit_x, exit_y = cand_x, cand_y
dist = d
if back_to_start and not second_round:
second_round = True
del self.r_x[-len(visited_x):]
del self.r_y[-len(visited_y):]
visited_x[:], visited_y[:] = [], []
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x.append(cand_x), visited_y.append(cand_y)
if cand_x == exit_x and \
cand_y == exit_y and \
second_round:
mov_dir = 'normal'
if show_animation:
plt.plot(self.r_x, self.r_y, "-r")
plt.pause(0.001)
if show_animation:
plt.show()
def bug2(self):
"""
Move towards goal in a greedy manner.
When you hit an obstacle, you go around it and
keep track of your distance from the goal.
If the distance from your goal was decreasing before
and now it starts increasing, that means the current
point is probably the closest point to the
goal (this may or may not be true because the algorithm
doesn't explore the entire boundary around the obstacle).
So, you depart from this point and continue towards the
goal in a greedy manner
"""
mov_dir = 'normal'
cand_x, cand_y = -np.inf, -np.inf
if show_animation:
plt.plot(self.obs_x, self.obs_y, ".k")
plt.plot(self.r_x[-1], self.r_y[-1], "og")
plt.plot(self.goal_x, self.goal_y, "xb")
plt.plot(self.out_x, self.out_y, ".")
straight_x, straight_y = [self.r_x[-1]], [self.r_y[-1]]
hit_x, hit_y = [], []
while True:
if straight_x[-1] == self.goal_x and \
straight_y[-1] == self.goal_y:
break
c_x = straight_x[-1] + np.sign(self.goal_x - straight_x[-1])
c_y = straight_y[-1] + np.sign(self.goal_y - straight_y[-1])
for x_ob, y_ob in zip(self.out_x, self.out_y):
if c_x == x_ob and c_y == y_ob:
hit_x.append(c_x), hit_y.append(c_y)
break
straight_x.append(c_x), straight_y.append(c_y)
if show_animation:
plt.plot(straight_x, straight_y, ",")
plt.plot(hit_x, hit_y, "d")
plt.grid(True)
plt.title('BUG 2')
for x_ob, y_ob in zip(self.out_x, self.out_y):
if self.r_x[-1] == x_ob and self.r_y[-1] == y_ob:
mov_dir = 'obs'
break
visited_x, visited_y = [], []
while True:
if self.r_x[-1] == self.goal_x \
and self.r_y[-1] == self.goal_y:
break
if mov_dir == 'normal':
cand_x, cand_y = self.mov_normal()
if mov_dir == 'obs':
cand_x, cand_y, _ = self.mov_to_next_obs(visited_x, visited_y)
if mov_dir == 'normal':
found_boundary = False
for x_ob, y_ob in zip(self.out_x, self.out_y):
if cand_x == x_ob and cand_y == y_ob:
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x[:], visited_y[:] = [], []
visited_x.append(cand_x), visited_y.append(cand_y)
del hit_x[0]
del hit_y[0]
mov_dir = 'obs'
found_boundary = True
break
if not found_boundary:
self.r_x.append(cand_x), self.r_y.append(cand_y)
elif mov_dir == 'obs':
self.r_x.append(cand_x), self.r_y.append(cand_y)
visited_x.append(cand_x), visited_y.append(cand_y)
for i_x, i_y in zip(range(len(hit_x)), range(len(hit_y))):
if cand_x == hit_x[i_x] and cand_y == hit_y[i_y]:
del hit_x[i_x]
del hit_y[i_y]
mov_dir = 'normal'
break
if show_animation:
plt.plot(self.r_x, self.r_y, "-r")
plt.pause(0.001)
if show_animation:
plt.show()
def main(bug_0, bug_1, bug_2):
# set obstacle positions
o_x, o_y = [], []
s_x = 0.0
s_y = 0.0
g_x = 167.0
g_y = 50.0
for i in range(20, 40):
for j in range(20, 40):
o_x.append(i)
o_y.append(j)
for i in range(60, 100):
for j in range(40, 80):
o_x.append(i)
o_y.append(j)
for i in range(120, 140):
for j in range(80, 100):
o_x.append(i)
o_y.append(j)
for i in range(80, 140):
for j in range(0, 20):
o_x.append(i)
o_y.append(j)
for i in range(0, 20):
for j in range(60, 100):
o_x.append(i)
o_y.append(j)
for i in range(20, 40):
for j in range(80, 100):
o_x.append(i)
o_y.append(j)
for i in range(120, 160):
for j in range(40, 60):
o_x.append(i)
o_y.append(j)
if bug_0:
my_Bug = BugPlanner(s_x, s_y, g_x, g_y, o_x, o_y)
my_Bug.bug0()
if bug_1:
my_Bug = BugPlanner(s_x, s_y, g_x, g_y, o_x, o_y)
my_Bug.bug1()
if bug_2:
my_Bug = BugPlanner(s_x, s_y, g_x, g_y, o_x, o_y)
my_Bug.bug2()
if __name__ == '__main__':
main(bug_0=True, bug_1=False, bug_2=False)
``` | /content/code_sandbox/PathPlanning/BugPlanning/bug.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,103 |
```python
"""
Reeds Shepp path planner sample code
author Atsushi Sakai(@Atsushi_twi)
co-author Videh Patel(@videh25) : Added the missing RS paths
"""
import math
import matplotlib.pyplot as plt
import numpy as np
from utils.angle import angle_mod
show_animation = True
class Path:
"""
Path data container
"""
def __init__(self):
# course segment length (negative value is backward segment)
self.lengths = []
# course segment type char ("S": straight, "L": left, "R": right)
self.ctypes = []
self.L = 0.0 # Total lengths of the path
self.x = [] # x positions
self.y = [] # y positions
self.yaw = [] # orientations [rad]
self.directions = [] # directions (1:forward, -1:backward)
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
if isinstance(x, list):
for (ix, iy, iyaw) in zip(x, y, yaw):
plot_arrow(ix, iy, iyaw)
else:
plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw), fc=fc,
ec=ec, head_width=width, head_length=width)
plt.plot(x, y)
def pi_2_pi(x):
return angle_mod(x)
def mod2pi(x):
# Be consistent with fmod in cplusplus here.
v = np.mod(x, np.copysign(2.0 * math.pi, x))
if v < -math.pi:
v += 2.0 * math.pi
else:
if v > math.pi:
v -= 2.0 * math.pi
return v
def set_path(paths, lengths, ctypes, step_size):
path = Path()
path.ctypes = ctypes
path.lengths = lengths
path.L = sum(np.abs(lengths))
# check same path exist
for i_path in paths:
type_is_same = (i_path.ctypes == path.ctypes)
length_is_close = (sum(np.abs(i_path.lengths)) - path.L) <= step_size
if type_is_same and length_is_close:
return paths # same path found, so do not insert path
# check path is long enough
if path.L <= step_size:
return paths # too short, so do not insert path
paths.append(path)
return paths
def polar(x, y):
r = math.hypot(x, y)
theta = math.atan2(y, x)
return r, theta
def left_straight_left(x, y, phi):
u, t = polar(x - math.sin(phi), y - 1.0 + math.cos(phi))
if 0.0 <= t <= math.pi:
v = mod2pi(phi - t)
if 0.0 <= v <= math.pi:
return True, [t, u, v], ['L', 'S', 'L']
return False, [], []
def left_straight_right(x, y, phi):
u1, t1 = polar(x + math.sin(phi), y - 1.0 - math.cos(phi))
u1 = u1 ** 2
if u1 >= 4.0:
u = math.sqrt(u1 - 4.0)
theta = math.atan2(2.0, u)
t = mod2pi(t1 + theta)
v = mod2pi(t - phi)
if (t >= 0.0) and (v >= 0.0):
return True, [t, u, v], ['L', 'S', 'R']
return False, [], []
def left_x_right_x_left(x, y, phi):
zeta = x - math.sin(phi)
eeta = y - 1 + math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 <= 4.0:
A = math.acos(0.25 * u1)
t = mod2pi(A + theta + math.pi/2)
u = mod2pi(math.pi - 2 * A)
v = mod2pi(phi - t - u)
return True, [t, -u, v], ['L', 'R', 'L']
return False, [], []
def left_x_right_left(x, y, phi):
zeta = x - math.sin(phi)
eeta = y - 1 + math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 <= 4.0:
A = math.acos(0.25 * u1)
t = mod2pi(A + theta + math.pi/2)
u = mod2pi(math.pi - 2*A)
v = mod2pi(-phi + t + u)
return True, [t, -u, -v], ['L', 'R', 'L']
return False, [], []
def left_right_x_left(x, y, phi):
zeta = x - math.sin(phi)
eeta = y - 1 + math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 <= 4.0:
u = math.acos(1 - u1**2 * 0.125)
A = math.asin(2 * math.sin(u) / u1)
t = mod2pi(-A + theta + math.pi/2)
v = mod2pi(t - u - phi)
return True, [t, u, -v], ['L', 'R', 'L']
return False, [], []
def left_right_x_left_right(x, y, phi):
zeta = x + math.sin(phi)
eeta = y - 1 - math.cos(phi)
u1, theta = polar(zeta, eeta)
# Solutions refering to (2 < u1 <= 4) are considered sub-optimal in paper
# Solutions do not exist for u1 > 4
if u1 <= 2:
A = math.acos((u1 + 2) * 0.25)
t = mod2pi(theta + A + math.pi/2)
u = mod2pi(A)
v = mod2pi(phi - t + 2*u)
if ((t >= 0) and (u >= 0) and (v >= 0)):
return True, [t, u, -u, -v], ['L', 'R', 'L', 'R']
return False, [], []
def left_x_right_left_x_right(x, y, phi):
zeta = x + math.sin(phi)
eeta = y - 1 - math.cos(phi)
u1, theta = polar(zeta, eeta)
u2 = (20 - u1**2) / 16
if (0 <= u2 <= 1):
u = math.acos(u2)
A = math.asin(2 * math.sin(u) / u1)
t = mod2pi(theta + A + math.pi/2)
v = mod2pi(t - phi)
if (t >= 0) and (v >= 0):
return True, [t, -u, -u, v], ['L', 'R', 'L', 'R']
return False, [], []
def left_x_right90_straight_left(x, y, phi):
zeta = x - math.sin(phi)
eeta = y - 1 + math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 >= 2.0:
u = math.sqrt(u1**2 - 4) - 2
A = math.atan2(2, math.sqrt(u1**2 - 4))
t = mod2pi(theta + A + math.pi/2)
v = mod2pi(t - phi + math.pi/2)
if (t >= 0) and (v >= 0):
return True, [t, -math.pi/2, -u, -v], ['L', 'R', 'S', 'L']
return False, [], []
def left_straight_right90_x_left(x, y, phi):
zeta = x - math.sin(phi)
eeta = y - 1 + math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 >= 2.0:
u = math.sqrt(u1**2 - 4) - 2
A = math.atan2(math.sqrt(u1**2 - 4), 2)
t = mod2pi(theta - A + math.pi/2)
v = mod2pi(t - phi - math.pi/2)
if (t >= 0) and (v >= 0):
return True, [t, u, math.pi/2, -v], ['L', 'S', 'R', 'L']
return False, [], []
def left_x_right90_straight_right(x, y, phi):
zeta = x + math.sin(phi)
eeta = y - 1 - math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 >= 2.0:
t = mod2pi(theta + math.pi/2)
u = u1 - 2
v = mod2pi(phi - t - math.pi/2)
if (t >= 0) and (v >= 0):
return True, [t, -math.pi/2, -u, -v], ['L', 'R', 'S', 'R']
return False, [], []
def left_straight_left90_x_right(x, y, phi):
zeta = x + math.sin(phi)
eeta = y - 1 - math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 >= 2.0:
t = mod2pi(theta)
u = u1 - 2
v = mod2pi(phi - t - math.pi/2)
if (t >= 0) and (v >= 0):
return True, [t, u, math.pi/2, -v], ['L', 'S', 'L', 'R']
return False, [], []
def left_x_right90_straight_left90_x_right(x, y, phi):
zeta = x + math.sin(phi)
eeta = y - 1 - math.cos(phi)
u1, theta = polar(zeta, eeta)
if u1 >= 4.0:
u = math.sqrt(u1**2 - 4) - 4
A = math.atan2(2, math.sqrt(u1**2 - 4))
t = mod2pi(theta + A + math.pi/2)
v = mod2pi(t - phi)
if (t >= 0) and (v >= 0):
return True, [t, -math.pi/2, -u, -math.pi/2, v], ['L', 'R', 'S', 'L', 'R']
return False, [], []
def timeflip(travel_distances):
return [-x for x in travel_distances]
def reflect(steering_directions):
def switch_dir(dirn):
if dirn == 'L':
return 'R'
elif dirn == 'R':
return 'L'
else:
return 'S'
return[switch_dir(dirn) for dirn in steering_directions]
def generate_path(q0, q1, max_curvature, step_size):
dx = q1[0] - q0[0]
dy = q1[1] - q0[1]
dth = q1[2] - q0[2]
c = math.cos(q0[2])
s = math.sin(q0[2])
x = (c * dx + s * dy) * max_curvature
y = (-s * dx + c * dy) * max_curvature
step_size *= max_curvature
paths = []
path_functions = [left_straight_left, left_straight_right, # CSC
left_x_right_x_left, left_x_right_left, left_right_x_left, # CCC
left_right_x_left_right, left_x_right_left_x_right, # CCCC
left_x_right90_straight_left, left_x_right90_straight_right, # CCSC
left_straight_right90_x_left, left_straight_left90_x_right, # CSCC
left_x_right90_straight_left90_x_right] # CCSCC
for path_func in path_functions:
flag, travel_distances, steering_dirns = path_func(x, y, dth)
if flag:
for distance in travel_distances:
if (0.1*sum([abs(d) for d in travel_distances]) < abs(distance) < step_size):
print("Step size too large for Reeds-Shepp paths.")
return []
paths = set_path(paths, travel_distances, steering_dirns, step_size)
flag, travel_distances, steering_dirns = path_func(-x, y, -dth)
if flag:
for distance in travel_distances:
if (0.1*sum([abs(d) for d in travel_distances]) < abs(distance) < step_size):
print("Step size too large for Reeds-Shepp paths.")
return []
travel_distances = timeflip(travel_distances)
paths = set_path(paths, travel_distances, steering_dirns, step_size)
flag, travel_distances, steering_dirns = path_func(x, -y, -dth)
if flag:
for distance in travel_distances:
if (0.1*sum([abs(d) for d in travel_distances]) < abs(distance) < step_size):
print("Step size too large for Reeds-Shepp paths.")
return []
steering_dirns = reflect(steering_dirns)
paths = set_path(paths, travel_distances, steering_dirns, step_size)
flag, travel_distances, steering_dirns = path_func(-x, -y, dth)
if flag:
for distance in travel_distances:
if (0.1*sum([abs(d) for d in travel_distances]) < abs(distance) < step_size):
print("Step size too large for Reeds-Shepp paths.")
return []
travel_distances = timeflip(travel_distances)
steering_dirns = reflect(steering_dirns)
paths = set_path(paths, travel_distances, steering_dirns, step_size)
return paths
def calc_interpolate_dists_list(lengths, step_size):
interpolate_dists_list = []
for length in lengths:
d_dist = step_size if length >= 0.0 else -step_size
interp_dists = np.arange(0.0, length, d_dist)
interp_dists = np.append(interp_dists, length)
interpolate_dists_list.append(interp_dists)
return interpolate_dists_list
def generate_local_course(lengths, modes, max_curvature, step_size):
interpolate_dists_list = calc_interpolate_dists_list(lengths, step_size * max_curvature)
origin_x, origin_y, origin_yaw = 0.0, 0.0, 0.0
xs, ys, yaws, directions = [], [], [], []
for (interp_dists, mode, length) in zip(interpolate_dists_list, modes,
lengths):
for dist in interp_dists:
x, y, yaw, direction = interpolate(dist, length, mode,
max_curvature, origin_x,
origin_y, origin_yaw)
xs.append(x)
ys.append(y)
yaws.append(yaw)
directions.append(direction)
origin_x = xs[-1]
origin_y = ys[-1]
origin_yaw = yaws[-1]
return xs, ys, yaws, directions
def interpolate(dist, length, mode, max_curvature, origin_x, origin_y,
origin_yaw):
if mode == "S":
x = origin_x + dist / max_curvature * math.cos(origin_yaw)
y = origin_y + dist / max_curvature * math.sin(origin_yaw)
yaw = origin_yaw
else: # curve
ldx = math.sin(dist) / max_curvature
ldy = 0.0
yaw = None
if mode == "L": # left turn
ldy = (1.0 - math.cos(dist)) / max_curvature
yaw = origin_yaw + dist
elif mode == "R": # right turn
ldy = (1.0 - math.cos(dist)) / -max_curvature
yaw = origin_yaw - dist
gdx = math.cos(-origin_yaw) * ldx + math.sin(-origin_yaw) * ldy
gdy = -math.sin(-origin_yaw) * ldx + math.cos(-origin_yaw) * ldy
x = origin_x + gdx
y = origin_y + gdy
return x, y, yaw, 1 if length > 0.0 else -1
def calc_paths(sx, sy, syaw, gx, gy, gyaw, maxc, step_size):
q0 = [sx, sy, syaw]
q1 = [gx, gy, gyaw]
paths = generate_path(q0, q1, maxc, step_size)
for path in paths:
xs, ys, yaws, directions = generate_local_course(path.lengths,
path.ctypes, maxc,
step_size)
# convert global coordinate
path.x = [math.cos(-q0[2]) * ix + math.sin(-q0[2]) * iy + q0[0] for
(ix, iy) in zip(xs, ys)]
path.y = [-math.sin(-q0[2]) * ix + math.cos(-q0[2]) * iy + q0[1] for
(ix, iy) in zip(xs, ys)]
path.yaw = [pi_2_pi(yaw + q0[2]) for yaw in yaws]
path.directions = directions
path.lengths = [length / maxc for length in path.lengths]
path.L = path.L / maxc
return paths
def reeds_shepp_path_planning(sx, sy, syaw, gx, gy, gyaw, maxc, step_size=0.2):
paths = calc_paths(sx, sy, syaw, gx, gy, gyaw, maxc, step_size)
if not paths:
return None, None, None, None, None # could not generate any path
# search minimum cost path
best_path_index = paths.index(min(paths, key=lambda p: abs(p.L)))
b_path = paths[best_path_index]
return b_path.x, b_path.y, b_path.yaw, b_path.ctypes, b_path.lengths
def main():
print("Reeds Shepp path planner sample start!!")
start_x = -1.0 # [m]
start_y = -4.0 # [m]
start_yaw = np.deg2rad(-20.0) # [rad]
end_x = 5.0 # [m]
end_y = 5.0 # [m]
end_yaw = np.deg2rad(25.0) # [rad]
curvature = 0.1
step_size = 0.05
xs, ys, yaws, modes, lengths = reeds_shepp_path_planning(start_x, start_y,
start_yaw, end_x,
end_y, end_yaw,
curvature,
step_size)
if not xs:
assert False, "No path"
if show_animation: # pragma: no cover
plt.cla()
plt.plot(xs, ys, label="final course " + str(modes))
print(f"{lengths=}")
# plotting
plot_arrow(start_x, start_y, start_yaw)
plot_arrow(end_x, end_y, end_yaw)
plt.legend()
plt.grid(True)
plt.axis("equal")
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/ReedsSheppPath/reeds_shepp_path_planning.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 4,471 |
```python
"""
Dubins path planner sample code
author Atsushi Sakai(@Atsushi_twi)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
from math import sin, cos, atan2, sqrt, acos, pi, hypot
import numpy as np
from utils.angle import angle_mod, rot_mat_2d
show_animation = True
def plan_dubins_path(s_x, s_y, s_yaw, g_x, g_y, g_yaw, curvature,
step_size=0.1, selected_types=None):
"""
Plan dubins path
Parameters
----------
s_x : float
x position of the start point [m]
s_y : float
y position of the start point [m]
s_yaw : float
yaw angle of the start point [rad]
g_x : float
x position of the goal point [m]
g_y : float
y position of the end point [m]
g_yaw : float
yaw angle of the end point [rad]
curvature : float
curvature for curve [1/m]
step_size : float (optional)
step size between two path points [m]. Default is 0.1
selected_types : a list of string or None
selected path planning types. If None, all types are used for
path planning, and minimum path length result is returned.
You can select used path plannings types by a string list.
e.g.: ["RSL", "RSR"]
Returns
-------
x_list: array
x positions of the path
y_list: array
y positions of the path
yaw_list: array
yaw angles of the path
modes: array
mode list of the path
lengths: array
arrow_length list of the path segments.
Examples
--------
You can generate a dubins path.
>>> start_x = 1.0 # [m]
>>> start_y = 1.0 # [m]
>>> start_yaw = np.deg2rad(45.0) # [rad]
>>> end_x = -3.0 # [m]
>>> end_y = -3.0 # [m]
>>> end_yaw = np.deg2rad(-45.0) # [rad]
>>> curvature = 1.0
>>> path_x, path_y, path_yaw, mode, _ = plan_dubins_path(
start_x, start_y, start_yaw, end_x, end_y, end_yaw, curvature)
>>> plt.plot(path_x, path_y, label="final course " + "".join(mode))
>>> plot_arrow(start_x, start_y, start_yaw)
>>> plot_arrow(end_x, end_y, end_yaw)
>>> plt.legend()
>>> plt.grid(True)
>>> plt.axis("equal")
>>> plt.show()
.. image:: dubins_path.jpg
"""
if selected_types is None:
planning_funcs = _PATH_TYPE_MAP.values()
else:
planning_funcs = [_PATH_TYPE_MAP[ptype] for ptype in selected_types]
# calculate local goal x, y, yaw
l_rot = rot_mat_2d(s_yaw)
le_xy = np.stack([g_x - s_x, g_y - s_y]).T @ l_rot
local_goal_x = le_xy[0]
local_goal_y = le_xy[1]
local_goal_yaw = g_yaw - s_yaw
lp_x, lp_y, lp_yaw, modes, lengths = _dubins_path_planning_from_origin(
local_goal_x, local_goal_y, local_goal_yaw, curvature, step_size,
planning_funcs)
# Convert a local coordinate path to the global coordinate
rot = rot_mat_2d(-s_yaw)
converted_xy = np.stack([lp_x, lp_y]).T @ rot
x_list = converted_xy[:, 0] + s_x
y_list = converted_xy[:, 1] + s_y
yaw_list = angle_mod(np.array(lp_yaw) + s_yaw)
return x_list, y_list, yaw_list, modes, lengths
def _mod2pi(theta):
return angle_mod(theta, zero_2_2pi=True)
def _calc_trig_funcs(alpha, beta):
sin_a = sin(alpha)
sin_b = sin(beta)
cos_a = cos(alpha)
cos_b = cos(beta)
cos_ab = cos(alpha - beta)
return sin_a, sin_b, cos_a, cos_b, cos_ab
def _LSL(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
mode = ["L", "S", "L"]
p_squared = 2 + d ** 2 - (2 * cos_ab) + (2 * d * (sin_a - sin_b))
if p_squared < 0: # invalid configuration
return None, None, None, mode
tmp = atan2((cos_b - cos_a), d + sin_a - sin_b)
d1 = _mod2pi(-alpha + tmp)
d2 = sqrt(p_squared)
d3 = _mod2pi(beta - tmp)
return d1, d2, d3, mode
def _RSR(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
mode = ["R", "S", "R"]
p_squared = 2 + d ** 2 - (2 * cos_ab) + (2 * d * (sin_b - sin_a))
if p_squared < 0:
return None, None, None, mode
tmp = atan2((cos_a - cos_b), d - sin_a + sin_b)
d1 = _mod2pi(alpha - tmp)
d2 = sqrt(p_squared)
d3 = _mod2pi(-beta + tmp)
return d1, d2, d3, mode
def _LSR(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
p_squared = -2 + d ** 2 + (2 * cos_ab) + (2 * d * (sin_a + sin_b))
mode = ["L", "S", "R"]
if p_squared < 0:
return None, None, None, mode
d1 = sqrt(p_squared)
tmp = atan2((-cos_a - cos_b), (d + sin_a + sin_b)) - atan2(-2.0, d1)
d2 = _mod2pi(-alpha + tmp)
d3 = _mod2pi(-_mod2pi(beta) + tmp)
return d2, d1, d3, mode
def _RSL(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
p_squared = d ** 2 - 2 + (2 * cos_ab) - (2 * d * (sin_a + sin_b))
mode = ["R", "S", "L"]
if p_squared < 0:
return None, None, None, mode
d1 = sqrt(p_squared)
tmp = atan2((cos_a + cos_b), (d - sin_a - sin_b)) - atan2(2.0, d1)
d2 = _mod2pi(alpha - tmp)
d3 = _mod2pi(beta - tmp)
return d2, d1, d3, mode
def _RLR(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
mode = ["R", "L", "R"]
tmp = (6.0 - d ** 2 + 2.0 * cos_ab + 2.0 * d * (sin_a - sin_b)) / 8.0
if abs(tmp) > 1.0:
return None, None, None, mode
d2 = _mod2pi(2 * pi - acos(tmp))
d1 = _mod2pi(alpha - atan2(cos_a - cos_b, d - sin_a + sin_b) + d2 / 2.0)
d3 = _mod2pi(alpha - beta - d1 + d2)
return d1, d2, d3, mode
def _LRL(alpha, beta, d):
sin_a, sin_b, cos_a, cos_b, cos_ab = _calc_trig_funcs(alpha, beta)
mode = ["L", "R", "L"]
tmp = (6.0 - d ** 2 + 2.0 * cos_ab + 2.0 * d * (- sin_a + sin_b)) / 8.0
if abs(tmp) > 1.0:
return None, None, None, mode
d2 = _mod2pi(2 * pi - acos(tmp))
d1 = _mod2pi(-alpha - atan2(cos_a - cos_b, d + sin_a - sin_b) + d2 / 2.0)
d3 = _mod2pi(_mod2pi(beta) - alpha - d1 + _mod2pi(d2))
return d1, d2, d3, mode
_PATH_TYPE_MAP = {"LSL": _LSL, "RSR": _RSR, "LSR": _LSR, "RSL": _RSL,
"RLR": _RLR, "LRL": _LRL, }
def _dubins_path_planning_from_origin(end_x, end_y, end_yaw, curvature,
step_size, planning_funcs):
dx = end_x
dy = end_y
d = hypot(dx, dy) * curvature
theta = _mod2pi(atan2(dy, dx))
alpha = _mod2pi(-theta)
beta = _mod2pi(end_yaw - theta)
best_cost = float("inf")
b_d1, b_d2, b_d3, b_mode = None, None, None, None
for planner in planning_funcs:
d1, d2, d3, mode = planner(alpha, beta, d)
if d1 is None:
continue
cost = (abs(d1) + abs(d2) + abs(d3))
if best_cost > cost: # Select minimum length one.
b_d1, b_d2, b_d3, b_mode, best_cost = d1, d2, d3, mode, cost
lengths = [b_d1, b_d2, b_d3]
x_list, y_list, yaw_list = _generate_local_course(lengths, b_mode,
curvature, step_size)
lengths = [length / curvature for length in lengths]
return x_list, y_list, yaw_list, b_mode, lengths
def _interpolate(length, mode, max_curvature, origin_x, origin_y,
origin_yaw, path_x, path_y, path_yaw):
if mode == "S":
path_x.append(origin_x + length / max_curvature * cos(origin_yaw))
path_y.append(origin_y + length / max_curvature * sin(origin_yaw))
path_yaw.append(origin_yaw)
else: # curve
ldx = sin(length) / max_curvature
ldy = 0.0
if mode == "L": # left turn
ldy = (1.0 - cos(length)) / max_curvature
elif mode == "R": # right turn
ldy = (1.0 - cos(length)) / -max_curvature
gdx = cos(-origin_yaw) * ldx + sin(-origin_yaw) * ldy
gdy = -sin(-origin_yaw) * ldx + cos(-origin_yaw) * ldy
path_x.append(origin_x + gdx)
path_y.append(origin_y + gdy)
if mode == "L": # left turn
path_yaw.append(origin_yaw + length)
elif mode == "R": # right turn
path_yaw.append(origin_yaw - length)
return path_x, path_y, path_yaw
def _generate_local_course(lengths, modes, max_curvature, step_size):
p_x, p_y, p_yaw = [0.0], [0.0], [0.0]
for (mode, length) in zip(modes, lengths):
if length == 0.0:
continue
# set origin state
origin_x, origin_y, origin_yaw = p_x[-1], p_y[-1], p_yaw[-1]
current_length = step_size
while abs(current_length + step_size) <= abs(length):
p_x, p_y, p_yaw = _interpolate(current_length, mode, max_curvature,
origin_x, origin_y, origin_yaw,
p_x, p_y, p_yaw)
current_length += step_size
p_x, p_y, p_yaw = _interpolate(length, mode, max_curvature, origin_x,
origin_y, origin_yaw, p_x, p_y, p_yaw)
return p_x, p_y, p_yaw
def main():
print("Dubins path planner sample start!!")
import matplotlib.pyplot as plt
from utils.plot import plot_arrow
start_x = 1.0 # [m]
start_y = 1.0 # [m]
start_yaw = np.deg2rad(45.0) # [rad]
end_x = -3.0 # [m]
end_y = -3.0 # [m]
end_yaw = np.deg2rad(-45.0) # [rad]
curvature = 1.0
path_x, path_y, path_yaw, mode, lengths = plan_dubins_path(start_x,
start_y,
start_yaw,
end_x,
end_y,
end_yaw,
curvature)
if show_animation:
plt.plot(path_x, path_y, label="".join(mode))
plot_arrow(start_x, start_y, start_yaw)
plot_arrow(end_x, end_y, end_yaw)
plt.legend()
plt.grid(True)
plt.axis("equal")
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/DubinsPath/dubins_path_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,151 |
```python
import math
import numpy as np
from scipy.interpolate import interp1d
from utils.angle import angle_mod
# motion parameter
L = 1.0 # wheel base
ds = 0.1 # course distance
v = 10.0 / 3.6 # velocity [m/s]
class State:
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
def pi_2_pi(angle):
return angle_mod(angle)
def update(state, v, delta, dt, L):
state.v = v
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 / L * math.tan(delta) * dt
state.yaw = pi_2_pi(state.yaw)
return state
def generate_trajectory(s, km, kf, k0):
n = s / ds
time = s / v # [s]
if isinstance(time, type(np.array([]))):
time = time[0]
if isinstance(km, type(np.array([]))):
km = km[0]
if isinstance(kf, type(np.array([]))):
kf = kf[0]
tk = np.array([0.0, time / 2.0, time])
kk = np.array([k0, km, kf])
t = np.arange(0.0, time, time / n)
fkp = interp1d(tk, kk, kind="quadratic")
kp = [fkp(ti) for ti in t]
dt = float(time / n)
# plt.plot(t, kp)
# plt.show()
state = State()
x, y, yaw = [state.x], [state.y], [state.yaw]
for ikp in kp:
state = update(state, v, ikp, dt, L)
x.append(state.x)
y.append(state.y)
yaw.append(state.yaw)
return x, y, yaw
def generate_last_state(s, km, kf, k0):
n = s / ds
time = s / v # [s]
if isinstance(n, type(np.array([]))):
n = n[0]
if isinstance(time, type(np.array([]))):
time = time[0]
if isinstance(km, type(np.array([]))):
km = km[0]
if isinstance(kf, type(np.array([]))):
kf = kf[0]
tk = np.array([0.0, time / 2.0, time])
kk = np.array([k0, km, kf])
t = np.arange(0.0, time, time / n)
fkp = interp1d(tk, kk, kind="quadratic")
kp = [fkp(ti) for ti in t]
dt = time / n
# plt.plot(t, kp)
# plt.show()
state = State()
_ = [update(state, v, ikp, dt, L) for ikp in kp]
return state.x, state.y, state.yaw
``` | /content/code_sandbox/PathPlanning/ModelPredictiveTrajectoryGenerator/motion_model.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 731 |
```python
"""
Model trajectory generator
author: Atsushi Sakai(@Atsushi_twi)
"""
import math
import matplotlib.pyplot as plt
import numpy as np
import sys
import pathlib
path_planning_dir = pathlib.Path(__file__).parent.parent
sys.path.append(str(path_planning_dir))
import ModelPredictiveTrajectoryGenerator.motion_model as motion_model
# optimization parameter
max_iter = 100
h: np.ndarray = np.array([0.5, 0.02, 0.02]).T # parameter sampling distance
cost_th = 0.1
show_animation = True
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): # pragma: no cover
"""
Plot arrow
"""
plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
fc=fc, ec=ec, head_width=width, head_length=width)
plt.plot(x, y)
plt.plot(0, 0)
def calc_diff(target, x, y, yaw):
d = np.array([target.x - x[-1],
target.y - y[-1],
motion_model.pi_2_pi(target.yaw - yaw[-1])])
return d
def calc_j(target, p, h, k0):
xp, yp, yawp = motion_model.generate_last_state(
p[0, 0] + h[0], p[1, 0], p[2, 0], k0)
dp = calc_diff(target, [xp], [yp], [yawp])
xn, yn, yawn = motion_model.generate_last_state(
p[0, 0] - h[0], p[1, 0], p[2, 0], k0)
dn = calc_diff(target, [xn], [yn], [yawn])
d1 = np.array((dp - dn) / (2.0 * h[0])).reshape(3, 1)
xp, yp, yawp = motion_model.generate_last_state(
p[0, 0], p[1, 0] + h[1], p[2, 0], k0)
dp = calc_diff(target, [xp], [yp], [yawp])
xn, yn, yawn = motion_model.generate_last_state(
p[0, 0], p[1, 0] - h[1], p[2, 0], k0)
dn = calc_diff(target, [xn], [yn], [yawn])
d2 = np.array((dp - dn) / (2.0 * h[1])).reshape(3, 1)
xp, yp, yawp = motion_model.generate_last_state(
p[0, 0], p[1, 0], p[2, 0] + h[2], k0)
dp = calc_diff(target, [xp], [yp], [yawp])
xn, yn, yawn = motion_model.generate_last_state(
p[0, 0], p[1, 0], p[2, 0] - h[2], k0)
dn = calc_diff(target, [xn], [yn], [yawn])
d3 = np.array((dp - dn) / (2.0 * h[2])).reshape(3, 1)
J = np.hstack((d1, d2, d3))
return J
def selection_learning_param(dp, p, k0, target):
mincost = float("inf")
mina = 1.0
maxa = 2.0
da = 0.5
for a in np.arange(mina, maxa, da):
tp = p + a * dp
xc, yc, yawc = motion_model.generate_last_state(
tp[0], tp[1], tp[2], k0)
dc = calc_diff(target, [xc], [yc], [yawc])
cost = np.linalg.norm(dc)
if cost <= mincost and a != 0.0:
mina = a
mincost = cost
# print(mincost, mina)
# input()
return mina
def show_trajectory(target, xc, yc): # pragma: no cover
plt.clf()
plot_arrow(target.x, target.y, target.yaw)
plt.plot(xc, yc, "-r")
plt.axis("equal")
plt.grid(True)
plt.pause(0.1)
def optimize_trajectory(target, k0, p):
for i in range(max_iter):
xc, yc, yawc = motion_model.generate_trajectory(p[0, 0], p[1, 0], p[2, 0], k0)
dc = np.array(calc_diff(target, xc, yc, yawc)).reshape(3, 1)
cost = np.linalg.norm(dc)
if cost <= cost_th:
print("path is ok cost is:" + str(cost))
break
J = calc_j(target, p, h, k0)
try:
dp = - np.linalg.inv(J) @ dc
except np.linalg.linalg.LinAlgError:
print("cannot calc path LinAlgError")
xc, yc, yawc, p = None, None, None, None
break
alpha = selection_learning_param(dp, p, k0, target)
p += alpha * np.array(dp)
# print(p.T)
if show_animation: # pragma: no cover
show_trajectory(target, xc, yc)
else:
xc, yc, yawc, p = None, None, None, None
print("cannot calc path")
return xc, yc, yawc, p
def optimize_trajectory_demo(): # pragma: no cover
# target = motion_model.State(x=5.0, y=2.0, yaw=np.deg2rad(00.0))
target = motion_model.State(x=5.0, y=2.0, yaw=np.deg2rad(90.0))
k0 = 0.0
init_p = np.array([6.0, 0.0, 0.0]).reshape(3, 1)
x, y, yaw, p = optimize_trajectory(target, k0, init_p)
if show_animation:
show_trajectory(target, x, y)
plot_arrow(target.x, target.y, target.yaw)
plt.axis("equal")
plt.grid(True)
plt.show()
def main(): # pragma: no cover
print(__file__ + " start!!")
optimize_trajectory_demo()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/ModelPredictiveTrajectoryGenerator/trajectory_generator.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,468 |
```python
"""
Lookup Table generation for model predictive trajectory generator
author: Atsushi Sakai
"""
import sys
import pathlib
path_planning_dir = pathlib.Path(__file__).parent.parent
sys.path.append(str(path_planning_dir))
from matplotlib import pyplot as plt
import numpy as np
import math
from ModelPredictiveTrajectoryGenerator import trajectory_generator,\
motion_model
def calc_states_list(max_yaw=np.deg2rad(-30.0)):
x = np.arange(10.0, 30.0, 5.0)
y = np.arange(0.0, 20.0, 2.0)
yaw = np.arange(-max_yaw, max_yaw, max_yaw)
states = []
for iyaw in yaw:
for iy in y:
for ix in x:
states.append([ix, iy, iyaw])
print("n_state:", len(states))
return states
def search_nearest_one_from_lookup_table(tx, ty, tyaw, lookup_table):
mind = float("inf")
minid = -1
for (i, table) in enumerate(lookup_table):
dx = tx - table[0]
dy = ty - table[1]
dyaw = tyaw - table[2]
d = math.sqrt(dx ** 2 + dy ** 2 + dyaw ** 2)
if d <= mind:
minid = i
mind = d
# print(minid)
return lookup_table[minid]
def save_lookup_table(file_name, table):
np.savetxt(file_name, np.array(table),
fmt='%s', delimiter=",", header="x,y,yaw,s,km,kf", comments="")
print("lookup table file is saved as " + file_name)
def generate_lookup_table():
states = calc_states_list(max_yaw=np.deg2rad(-30.0))
k0 = 0.0
# x, y, yaw, s, km, kf
lookup_table = [[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]]
for state in states:
best_p = search_nearest_one_from_lookup_table(
state[0], state[1], state[2], lookup_table)
target = motion_model.State(x=state[0], y=state[1], yaw=state[2])
init_p = np.array(
[np.hypot(state[0], state[1]), best_p[4], best_p[5]]).reshape(3, 1)
x, y, yaw, p = trajectory_generator.optimize_trajectory(target,
k0, init_p)
if x is not None:
print("find good path")
lookup_table.append(
[x[-1], y[-1], yaw[-1], float(p[0, 0]), float(p[1, 0]), float(p[2, 0])])
print("finish lookup table generation")
save_lookup_table("lookup_table.csv", lookup_table)
for table in lookup_table:
x_c, y_c, yaw_c = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
plt.plot(x_c, y_c, "-r")
x_c, y_c, yaw_c = motion_model.generate_trajectory(
table[3], -table[4], -table[5], k0)
plt.plot(x_c, y_c, "-r")
plt.grid(True)
plt.axis("equal")
plt.show()
print("Done")
def main():
generate_lookup_table()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/ModelPredictiveTrajectoryGenerator/lookup_table_generator.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 787 |
```python
"""
Author: Jonathan Schwartz (github.com/SchwartzCode)
This code provides a simple implementation of Dynamic Movement
Primitives, which is an approach to learning curves by modelling
them as a weighted sum of gaussian distributions. This approach
can be used to dampen noise in a curve, and can also be used to
stretch a curve by adjusting its start and end points.
More information on Dynamic Movement Primitives available at:
path_to_url
path_to_url
"""
from matplotlib import pyplot as plt
import numpy as np
class DMP(object):
def __init__(self, training_data, data_period, K=156.25, B=25):
"""
Arguments:
training_data - input data of form [N, dim]
data_period - amount of time training data covers
K and B - spring and damper constants to define
DMP behavior
"""
self.K = K # virtual spring constant
self.B = B # virtual damper coefficient
self.timesteps = training_data.shape[0]
self.dt = data_period / self.timesteps
self.weights = None # weights used to generate DMP trajectories
self.T_orig = data_period
self.training_data = training_data
self.find_basis_functions_weights(training_data, data_period)
def find_basis_functions_weights(self, training_data, data_period,
num_weights=10):
"""
Arguments:
data [(steps x spacial dim) np array] - data to replicate with DMP
data_period [float] - time duration of data
"""
if not isinstance(training_data, np.ndarray):
print("Warning: you should input training data as an np.ndarray")
elif training_data.shape[0] < training_data.shape[1]:
print("Warning: you probably need to transpose your training data")
dt = data_period / len(training_data)
init_state = training_data[0]
goal_state = training_data[-1]
# means (C) and std devs (H) of gaussian basis functions
C = np.linspace(0, 1, num_weights)
H = (0.65*(1./(num_weights-1))**2)
for dim, _ in enumerate(training_data[0]):
dimension_data = training_data[:, dim]
q0 = init_state[dim]
g = goal_state[dim]
q = q0
qd_last = 0
phi_vals = []
f_vals = []
for i, _ in enumerate(dimension_data):
if i + 1 == len(dimension_data):
qd = 0
else:
qd = (dimension_data[i+1] - dimension_data[i]) / dt
phi = [np.exp(-0.5 * ((i * dt / data_period) - c)**2 / H)
for c in C]
phi = phi/np.sum(phi)
qdd = (qd - qd_last)/dt
f = (qdd * data_period**2 - self.K * (g - q) + self.B * qd
* data_period) / (g - q0)
phi_vals.append(phi)
f_vals.append(f)
qd_last = qd
q += qd * dt
phi_vals = np.asarray(phi_vals)
f_vals = np.asarray(f_vals)
w = np.linalg.lstsq(phi_vals, f_vals, rcond=None)
if self.weights is None:
self.weights = np.asarray(w[0])
else:
self.weights = np.vstack([self.weights, w[0]])
def recreate_trajectory(self, init_state, goal_state, T):
"""
init_state - initial state/position
goal_state - goal state/position
T - amount of time to travel q0 -> g
"""
nrBasis = len(self.weights[0]) # number of gaussian basis functions
# means (C) and std devs (H) of gaussian basis functions
C = np.linspace(0, 1, nrBasis)
H = (0.65*(1./(nrBasis-1))**2)
# initialize virtual system
time = 0
q = init_state
dimensions = self.weights.shape[0]
qd = np.zeros(dimensions)
positions = np.array([])
for k in range(self.timesteps):
time = time + self.dt
qdd = np.zeros(dimensions)
for dim in range(dimensions):
if time <= T:
phi = [np.exp(-0.5 * ((time / T) - c)**2 / H) for c in C]
phi = phi / np.sum(phi)
f = np.dot(phi, self.weights[dim])
else:
f = 0
# simulate dynamics
qdd[dim] = (self.K*(goal_state[dim] - q[dim])/T**2
- self.B*qd[dim]/T
+ (goal_state[dim] - init_state[dim])*f/T**2)
qd = qd + qdd * self.dt
q = q + qd * self.dt
if positions.size == 0:
positions = q
else:
positions = np.vstack([positions, q])
t = np.arange(0, self.timesteps * self.dt, self.dt)
return t, positions
@staticmethod
def dist_between(p1, p2):
return np.linalg.norm(p1 - p2)
def view_trajectory(self, path, title=None, demo=False):
path = np.asarray(path)
plt.cla()
plt.plot(self.training_data[:, 0], self.training_data[:, 1],
label="Training Data")
plt.plot(path[:, 0], path[:, 1],
linewidth=2, label="DMP Approximation")
plt.xlabel("X Position")
plt.ylabel("Y Position")
plt.legend()
if title is not None:
plt.title(title)
if demo:
plt.xlim([-0.5, 5])
plt.ylim([-2, 2])
plt.draw()
plt.pause(0.02)
else:
plt.show()
def show_DMP_purpose(self):
"""
This function conveys the purpose of DMPs:
to capture a trajectory and be able to stretch
and squeeze it in terms of start and stop position
or time
"""
q0_orig = self.training_data[0]
g_orig = self.training_data[-1]
T_orig = self.T_orig
data_range = (np.amax(self.training_data[:, 0])
- np.amin(self.training_data[:, 0])) / 4
q0_right = q0_orig + np.array([data_range, 0])
q0_up = q0_orig + np.array([0, data_range/2])
g_left = g_orig - np.array([data_range, 0])
g_down = g_orig - np.array([0, data_range/2])
q0_vals = np.vstack([np.linspace(q0_orig, q0_right, 20),
np.linspace(q0_orig, q0_up, 20)])
g_vals = np.vstack([np.linspace(g_orig, g_left, 20),
np.linspace(g_orig, g_down, 20)])
T_vals = np.linspace(T_orig, 2*T_orig, 20)
for new_q0_value in q0_vals:
plot_title = "Initial Position = [%s, %s]" % \
(round(new_q0_value[0], 2), round(new_q0_value[1], 2))
_, path = self.recreate_trajectory(new_q0_value, g_orig, T_orig)
self.view_trajectory(path, title=plot_title, demo=True)
for new_g_value in g_vals:
plot_title = "Goal Position = [%s, %s]" % \
(round(new_g_value[0], 2), round(new_g_value[1], 2))
_, path = self.recreate_trajectory(q0_orig, new_g_value, T_orig)
self.view_trajectory(path, title=plot_title, demo=True)
for new_T_value in T_vals:
plot_title = "Period = %s [sec]" % round(new_T_value, 2)
_, path = self.recreate_trajectory(q0_orig, g_orig, new_T_value)
self.view_trajectory(path, title=plot_title, demo=True)
def example_DMP():
"""
Creates a noisy trajectory, fits weights to it, and then adjusts the
trajectory by moving its start position, goal position, or period
"""
t = np.arange(0, 3*np.pi/2, 0.01)
t1 = np.arange(3*np.pi/2, 2*np.pi, 0.01)[:-1]
t2 = np.arange(0, np.pi/2, 0.01)[:-1]
t3 = np.arange(np.pi, 3*np.pi/2, 0.01)
data_x = t + 0.02*np.random.rand(t.shape[0])
data_y = np.concatenate([np.cos(t1) + 0.1*np.random.rand(t1.shape[0]),
np.cos(t2) + 0.1*np.random.rand(t2.shape[0]),
np.sin(t3) + 0.1*np.random.rand(t3.shape[0])])
training_data = np.vstack([data_x, data_y]).T
period = 3*np.pi/2
DMP_controller = DMP(training_data, period)
DMP_controller.show_DMP_purpose()
if __name__ == '__main__':
example_DMP()
``` | /content/code_sandbox/PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,093 |
```python
"""
Path Planner with B-Spline
author: Atsushi Sakai (@Atsushi_twi)
"""
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interpolate
from utils.plot import plot_curvature
def approximate_b_spline_path(x: list,
y: list,
n_path_points: int,
degree: int = 3,
s=None,
) -> tuple:
"""
Approximate points with a B-Spline path
Parameters
----------
x : array_like
x position list of approximated points
y : array_like
y position list of approximated points
n_path_points : int
number of path points
degree : int, optional
B Spline curve degree. Must be 2<= k <= 5. Default: 3.
s : int, optional
smoothing parameter. If this value is bigger, the path will be
smoother, but it will be less accurate. If this value is smaller,
the path will be more accurate, but it will be less smooth.
When `s` is 0, it is equivalent to the interpolation. Default is None,
in this case `s` will be `len(x)`.
Returns
-------
x : array
x positions of the result path
y : array
y positions of the result path
heading : array
heading of the result path
curvature : array
curvature of the result path
"""
distances = _calc_distance_vector(x, y)
spl_i_x = interpolate.UnivariateSpline(distances, x, k=degree, s=s)
spl_i_y = interpolate.UnivariateSpline(distances, y, k=degree, s=s)
sampled = np.linspace(0.0, distances[-1], n_path_points)
return _evaluate_spline(sampled, spl_i_x, spl_i_y)
def interpolate_b_spline_path(x, y,
n_path_points: int,
degree: int = 3) -> tuple:
"""
Interpolate x-y points with a B-Spline path
Parameters
----------
x : array_like
x positions of interpolated points
y : array_like
y positions of interpolated points
n_path_points : int
number of path points
degree : int, optional
B-Spline degree. Must be 2<= k <= 5. Default: 3
Returns
-------
x : array
x positions of the result path
y : array
y positions of the result path
heading : array
heading of the result path
curvature : array
curvature of the result path
"""
return approximate_b_spline_path(x, y, n_path_points, degree, s=0.0)
def _calc_distance_vector(x, y):
dx, dy = np.diff(x), np.diff(y)
distances = np.cumsum([np.hypot(idx, idy) for idx, idy in zip(dx, dy)])
distances = np.concatenate(([0.0], distances))
distances /= distances[-1]
return distances
def _evaluate_spline(sampled, spl_i_x, spl_i_y):
x = spl_i_x(sampled)
y = spl_i_y(sampled)
dx = spl_i_x.derivative(1)(sampled)
dy = spl_i_y.derivative(1)(sampled)
heading = np.arctan2(dy, dx)
ddx = spl_i_x.derivative(2)(sampled)
ddy = spl_i_y.derivative(2)(sampled)
curvature = (ddy * dx - ddx * dy) / np.power(dx * dx + dy * dy, 2.0 / 3.0)
return np.array(x), y, heading, curvature,
def main():
print(__file__ + " start!!")
# way points
way_point_x = [-1.0, 3.0, 4.0, 2.0, 1.0]
way_point_y = [0.0, -3.0, 1.0, 1.0, 3.0]
n_course_point = 50 # sampling number
plt.subplots()
rax, ray, heading, curvature = approximate_b_spline_path(
way_point_x, way_point_y, n_course_point, s=0.5)
plt.plot(rax, ray, '-r', label="Approximated B-Spline path")
plot_curvature(rax, ray, heading, curvature)
plt.title("B-Spline approximation")
plt.plot(way_point_x, way_point_y, '-og', label="way points")
plt.grid(True)
plt.legend()
plt.axis("equal")
plt.subplots()
rix, riy, heading, curvature = interpolate_b_spline_path(
way_point_x, way_point_y, n_course_point)
plt.plot(rix, riy, '-b', label="Interpolated B-Spline path")
plot_curvature(rix, riy, heading, curvature)
plt.title("B-Spline interpolation")
plt.plot(way_point_x, way_point_y, '-og', label="way points")
plt.grid(True)
plt.legend()
plt.axis("equal")
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/BSplinePath/bspline_path.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,184 |
```python
"""
Path planning with Bezier curve.
author: Atsushi Sakai(@Atsushi_twi)
"""
import matplotlib.pyplot as plt
import numpy as np
import scipy.special
show_animation = True
def calc_4points_bezier_path(sx, sy, syaw, ex, ey, eyaw, offset):
"""
Compute control points and path given start and end position.
:param sx: (float) x-coordinate of the starting point
:param sy: (float) y-coordinate of the starting point
:param syaw: (float) yaw angle at start
:param ex: (float) x-coordinate of the ending point
:param ey: (float) y-coordinate of the ending point
:param eyaw: (float) yaw angle at the end
:param offset: (float)
:return: (numpy array, numpy array)
"""
dist = np.hypot(sx - ex, sy - ey) / offset
control_points = np.array(
[[sx, sy],
[sx + dist * np.cos(syaw), sy + dist * np.sin(syaw)],
[ex - dist * np.cos(eyaw), ey - dist * np.sin(eyaw)],
[ex, ey]])
path = calc_bezier_path(control_points, n_points=100)
return path, control_points
def calc_bezier_path(control_points, n_points=100):
"""
Compute bezier path (trajectory) given control points.
:param control_points: (numpy array)
:param n_points: (int) number of points in the trajectory
:return: (numpy array)
"""
traj = []
for t in np.linspace(0, 1, n_points):
traj.append(bezier(t, control_points))
return np.array(traj)
def bernstein_poly(n, i, t):
"""
Bernstein polynom.
:param n: (int) polynom degree
:param i: (int)
:param t: (float)
:return: (float)
"""
return scipy.special.comb(n, i) * t ** i * (1 - t) ** (n - i)
def bezier(t, control_points):
"""
Return one point on the bezier curve.
:param t: (float) number in [0, 1]
:param control_points: (numpy array)
:return: (numpy array) Coordinates of the point
"""
n = len(control_points) - 1
return np.sum([bernstein_poly(n, i, t) * control_points[i] for i in range(n + 1)], axis=0)
def bezier_derivatives_control_points(control_points, n_derivatives):
"""
Compute control points of the successive derivatives of a given bezier curve.
A derivative of a bezier curve is a bezier curve.
See path_to_url#derivatives
for detailed explanations
:param control_points: (numpy array)
:param n_derivatives: (int)
e.g., n_derivatives=2 -> compute control points for first and second derivatives
:return: ([numpy array])
"""
w = {0: control_points}
for i in range(n_derivatives):
n = len(w[i])
w[i + 1] = np.array([(n - 1) * (w[i][j + 1] - w[i][j])
for j in range(n - 1)])
return w
def curvature(dx, dy, ddx, ddy):
"""
Compute curvature at one point given first and second derivatives.
:param dx: (float) First derivative along x axis
:param dy: (float)
:param ddx: (float) Second derivative along x axis
:param ddy: (float)
:return: (float)
"""
return (dx * ddy - dy * ddx) / (dx ** 2 + dy ** 2) ** (3 / 2)
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): # pragma: no cover
"""Plot arrow."""
if not isinstance(x, float):
for (ix, iy, iyaw) in zip(x, y, yaw):
plot_arrow(ix, iy, iyaw)
else:
plt.arrow(x, y, length * np.cos(yaw), length * np.sin(yaw),
fc=fc, ec=ec, head_width=width, head_length=width)
plt.plot(x, y)
def main():
"""Plot an example bezier curve."""
start_x = 10.0 # [m]
start_y = 1.0 # [m]
start_yaw = np.radians(180.0) # [rad]
end_x = -0.0 # [m]
end_y = -3.0 # [m]
end_yaw = np.radians(-45.0) # [rad]
offset = 3.0
path, control_points = calc_4points_bezier_path(
start_x, start_y, start_yaw, end_x, end_y, end_yaw, offset)
# Note: alternatively, instead of specifying start and end position
# you can directly define n control points and compute the path:
# control_points = np.array([[5., 1.], [-2.78, 1.], [-11.5, -4.5], [-6., -8.]])
# path = calc_bezier_path(control_points, n_points=100)
# Display the tangent, normal and radius of cruvature at a given point
t = 0.86 # Number in [0, 1]
x_target, y_target = bezier(t, control_points)
derivatives_cp = bezier_derivatives_control_points(control_points, 2)
point = bezier(t, control_points)
dt = bezier(t, derivatives_cp[1])
ddt = bezier(t, derivatives_cp[2])
# Radius of curvature
radius = 1 / curvature(dt[0], dt[1], ddt[0], ddt[1])
# Normalize derivative
dt /= np.linalg.norm(dt, 2)
tangent = np.array([point, point + dt])
normal = np.array([point, point + [- dt[1], dt[0]]])
curvature_center = point + np.array([- dt[1], dt[0]]) * radius
circle = plt.Circle(tuple(curvature_center), radius,
color=(0, 0.8, 0.8), fill=False, linewidth=1)
assert path.T[0][0] == start_x, "path is invalid"
assert path.T[1][0] == start_y, "path is invalid"
assert path.T[0][-1] == end_x, "path is invalid"
assert path.T[1][-1] == end_y, "path is invalid"
if show_animation: # pragma: no cover
fig, ax = plt.subplots()
ax.plot(path.T[0], path.T[1], label="Bezier Path")
ax.plot(control_points.T[0], control_points.T[1],
'--o', label="Control Points")
ax.plot(x_target, y_target)
ax.plot(tangent[:, 0], tangent[:, 1], label="Tangent")
ax.plot(normal[:, 0], normal[:, 1], label="Normal")
ax.add_artist(circle)
plot_arrow(start_x, start_y, start_yaw)
plot_arrow(end_x, end_y, end_yaw)
ax.legend()
ax.axis("equal")
ax.grid(True)
plt.show()
def main2():
"""Show the effect of the offset."""
start_x = 10.0 # [m]
start_y = 1.0 # [m]
start_yaw = np.radians(180.0) # [rad]
end_x = -0.0 # [m]
end_y = -3.0 # [m]
end_yaw = np.radians(-45.0) # [rad]
for offset in np.arange(1.0, 5.0, 1.0):
path, control_points = calc_4points_bezier_path(
start_x, start_y, start_yaw, end_x, end_y, end_yaw, offset)
assert path.T[0][0] == start_x, "path is invalid"
assert path.T[1][0] == start_y, "path is invalid"
assert path.T[0][-1] == end_x, "path is invalid"
assert path.T[1][-1] == end_y, "path is invalid"
if show_animation: # pragma: no cover
plt.plot(path.T[0], path.T[1], label="Offset=" + str(offset))
if show_animation: # pragma: no cover
plot_arrow(start_x, start_y, start_yaw)
plot_arrow(end_x, end_y, end_yaw)
plt.legend()
plt.axis("equal")
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
# main2()
``` | /content/code_sandbox/PathPlanning/BezierPath/bezier_path.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,998 |
```python
"""
Probabilistic Road Map (PRM) Planner
author: Atsushi Sakai (@Atsushi_twi)
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import KDTree
# parameter
N_SAMPLE = 500 # number of sample_points
N_KNN = 10 # number of edge from one sampled point
MAX_EDGE_LEN = 30.0 # [m] Maximum edge length
show_animation = True
class Node:
"""
Node class for dijkstra search
"""
def __init__(self, x, y, cost, parent_index):
self.x = x
self.y = y
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," +\
str(self.cost) + "," + str(self.parent_index)
def prm_planning(start_x, start_y, goal_x, goal_y,
obstacle_x_list, obstacle_y_list, robot_radius, *, rng=None):
"""
Run probabilistic road map planning
:param start_x: start x position
:param start_y: start y position
:param goal_x: goal x position
:param goal_y: goal y position
:param obstacle_x_list: obstacle x positions
:param obstacle_y_list: obstacle y positions
:param robot_radius: robot radius
:param rng: (Optional) Random generator
:return:
"""
obstacle_kd_tree = KDTree(np.vstack((obstacle_x_list, obstacle_y_list)).T)
sample_x, sample_y = sample_points(start_x, start_y, goal_x, goal_y,
robot_radius,
obstacle_x_list, obstacle_y_list,
obstacle_kd_tree, rng)
if show_animation:
plt.plot(sample_x, sample_y, ".b")
road_map = generate_road_map(sample_x, sample_y,
robot_radius, obstacle_kd_tree)
rx, ry = dijkstra_planning(
start_x, start_y, goal_x, goal_y, road_map, sample_x, sample_y)
return rx, ry
def is_collision(sx, sy, gx, gy, rr, obstacle_kd_tree):
x = sx
y = sy
dx = gx - sx
dy = gy - sy
yaw = math.atan2(gy - sy, gx - sx)
d = math.hypot(dx, dy)
if d >= MAX_EDGE_LEN:
return True
D = rr
n_step = round(d / D)
for i in range(n_step):
dist, _ = obstacle_kd_tree.query([x, y])
if dist <= rr:
return True # collision
x += D * math.cos(yaw)
y += D * math.sin(yaw)
# goal point check
dist, _ = obstacle_kd_tree.query([gx, gy])
if dist <= rr:
return True # collision
return False # OK
def generate_road_map(sample_x, sample_y, rr, obstacle_kd_tree):
"""
Road map generation
sample_x: [m] x positions of sampled points
sample_y: [m] y positions of sampled points
robot_radius: Robot Radius[m]
obstacle_kd_tree: KDTree object of obstacles
"""
road_map = []
n_sample = len(sample_x)
sample_kd_tree = KDTree(np.vstack((sample_x, sample_y)).T)
for (i, ix, iy) in zip(range(n_sample), sample_x, sample_y):
dists, indexes = sample_kd_tree.query([ix, iy], k=n_sample)
edge_id = []
for ii in range(1, len(indexes)):
nx = sample_x[indexes[ii]]
ny = sample_y[indexes[ii]]
if not is_collision(ix, iy, nx, ny, rr, obstacle_kd_tree):
edge_id.append(indexes[ii])
if len(edge_id) >= N_KNN:
break
road_map.append(edge_id)
# plot_road_map(road_map, sample_x, sample_y)
return road_map
def dijkstra_planning(sx, sy, gx, gy, road_map, sample_x, sample_y):
"""
s_x: start x position [m]
s_y: start y position [m]
goal_x: goal x position [m]
goal_y: goal y position [m]
obstacle_x_list: x position list of Obstacles [m]
obstacle_y_list: y position list of Obstacles [m]
robot_radius: robot radius [m]
road_map: ??? [m]
sample_x: ??? [m]
sample_y: ??? [m]
@return: Two lists of path coordinates ([x1, x2, ...], [y1, y2, ...]), empty list when no path was found
"""
start_node = Node(sx, sy, 0.0, -1)
goal_node = Node(gx, gy, 0.0, -1)
open_set, closed_set = dict(), dict()
open_set[len(road_map) - 2] = start_node
path_found = True
while True:
if not open_set:
print("Cannot find path")
path_found = False
break
c_id = min(open_set, key=lambda o: open_set[o].cost)
current = open_set[c_id]
# show graph
if show_animation and len(closed_set.keys()) % 2 == 0:
# 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(current.x, current.y, "xg")
plt.pause(0.001)
if c_id == (len(road_map) - 1):
print("goal is found!")
goal_node.parent_index = current.parent_index
goal_node.cost = current.cost
break
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
# expand search grid based on motion model
for i in range(len(road_map[c_id])):
n_id = road_map[c_id][i]
dx = sample_x[n_id] - current.x
dy = sample_y[n_id] - current.y
d = math.hypot(dx, dy)
node = Node(sample_x[n_id], sample_y[n_id],
current.cost + d, c_id)
if n_id in closed_set:
continue
# Otherwise if it is already in the open set
if n_id in open_set:
if open_set[n_id].cost > node.cost:
open_set[n_id].cost = node.cost
open_set[n_id].parent_index = c_id
else:
open_set[n_id] = node
if path_found is False:
return [], []
# generate final course
rx, ry = [goal_node.x], [goal_node.y]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(n.x)
ry.append(n.y)
parent_index = n.parent_index
return rx, ry
def plot_road_map(road_map, sample_x, sample_y): # pragma: no cover
for i, _ in enumerate(road_map):
for ii in range(len(road_map[i])):
ind = road_map[i][ii]
plt.plot([sample_x[i], sample_x[ind]],
[sample_y[i], sample_y[ind]], "-k")
def sample_points(sx, sy, gx, gy, rr, ox, oy, obstacle_kd_tree, rng):
max_x = max(ox)
max_y = max(oy)
min_x = min(ox)
min_y = min(oy)
sample_x, sample_y = [], []
if rng is None:
rng = np.random.default_rng()
while len(sample_x) <= N_SAMPLE:
tx = (rng.random() * (max_x - min_x)) + min_x
ty = (rng.random() * (max_y - min_y)) + min_y
dist, index = obstacle_kd_tree.query([tx, ty])
if dist >= rr:
sample_x.append(tx)
sample_y.append(ty)
sample_x.append(sx)
sample_y.append(sy)
sample_x.append(gx)
sample_y.append(gy)
return sample_x, sample_y
def main(rng=None):
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
robot_size = 5.0 # [m]
ox = []
oy = []
for i in range(60):
ox.append(i)
oy.append(0.0)
for i in range(60):
ox.append(60.0)
oy.append(i)
for i in range(61):
ox.append(i)
oy.append(60.0)
for i in range(61):
ox.append(0.0)
oy.append(i)
for i in range(40):
ox.append(20.0)
oy.append(i)
for i in range(40):
ox.append(40.0)
oy.append(60.0 - i)
if show_animation:
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "^r")
plt.plot(gx, gy, "^c")
plt.grid(True)
plt.axis("equal")
rx, ry = prm_planning(sx, sy, gx, gy, ox, oy, robot_size, rng=rng)
assert rx, 'Cannot found path'
if show_animation:
plt.plot(rx, ry, "-r")
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/ProbabilisticRoadMap/probabilistic_road_map.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,240 |
```python
"""
Grid based Dijkstra planning
author: Atsushi Sakai(@Atsushi_twi)
"""
import matplotlib.pyplot as plt
import math
show_animation = True
class Dijkstra:
def __init__(self, ox, oy, resolution, robot_radius):
"""
Initialize map for a star planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.min_x = None
self.min_y = None
self.max_x = None
self.max_y = None
self.x_width = None
self.y_width = None
self.obstacle_map = None
self.resolution = resolution
self.robot_radius = robot_radius
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index # index of previous Node
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
dijkstra path search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gx: goal x position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1)
open_set, closed_set = dict(), dict()
open_set[self.calc_index(start_node)] = start_node
while True:
c_id = min(open_set, key=lambda o: open_set[o].cost)
current = open_set[c_id]
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_position(current.x, self.min_x),
self.calc_position(current.y, self.min_y), "xc")
# 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 len(closed_set.keys()) % 10 == 0:
plt.pause(0.001)
if current.x == goal_node.x and current.y == goal_node.y:
print("Find goal")
goal_node.parent_index = current.parent_index
goal_node.cost = current.cost
break
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
# expand search grid based on motion model
for move_x, move_y, move_cost in self.motion:
node = self.Node(current.x + move_x,
current.y + move_y,
current.cost + move_cost, c_id)
n_id = self.calc_index(node)
if n_id in closed_set:
continue
if not self.verify_node(node):
continue
if n_id not in open_set:
open_set[n_id] = node # Discover a new node
else:
if open_set[n_id].cost >= node.cost:
# This path is the best until now. record it!
open_set[n_id] = node
rx, ry = self.calc_final_path(goal_node, closed_set)
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_position(goal_node.x, self.min_x)], [
self.calc_position(goal_node.y, self.min_y)]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(self.calc_position(n.x, self.min_x))
ry.append(self.calc_position(n.y, self.min_y))
parent_index = n.parent_index
return rx, ry
def calc_position(self, index, minp):
pos = index * self.resolution + minp
return pos
def calc_xy_index(self, position, minp):
return round((position - minp) / self.resolution)
def calc_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_position(node.x, self.min_x)
py = self.calc_position(node.y, self.min_y)
if px < self.min_x:
return False
if py < self.min_y:
return False
if px >= self.max_x:
return False
if py >= self.max_y:
return False
if self.obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
# obstacle map generation
self.obstacle_map = [[False for _ in range(self.y_width)]
for _ in range(self.x_width)]
for ix in range(self.x_width):
x = self.calc_position(ix, self.min_x)
for iy in range(self.y_width):
y = self.calc_position(iy, self.min_y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.robot_radius:
self.obstacle_map[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = -5.0 # [m]
sy = -5.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
dijkstra = Dijkstra(ox, oy, grid_size, robot_radius)
rx, ry = dijkstra.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/Dijkstra/dijkstra.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,947 |
```python
"""
Frenet optimal trajectory generator
author: Atsushi Sakai (@Atsushi_twi)
Ref:
- [Optimal Trajectory Generation for Dynamic Street Scenarios in a Frenet Frame]
(path_to_url
- [Optimal trajectory generation for dynamic street scenarios in a Frenet Frame]
(path_to_url
"""
import numpy as np
import matplotlib.pyplot as plt
import copy
import math
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from QuinticPolynomialsPlanner.quintic_polynomials_planner import \
QuinticPolynomial
from CubicSpline import cubic_spline_planner
SIM_LOOP = 500
# Parameter
MAX_SPEED = 50.0 / 3.6 # maximum speed [m/s]
MAX_ACCEL = 2.0 # maximum acceleration [m/ss]
MAX_CURVATURE = 1.0 # maximum curvature [1/m]
MAX_ROAD_WIDTH = 7.0 # maximum road width [m]
D_ROAD_W = 1.0 # road width sampling length [m]
DT = 0.2 # time tick [s]
MAX_T = 5.0 # max prediction time [m]
MIN_T = 4.0 # min prediction time [m]
TARGET_SPEED = 30.0 / 3.6 # target speed [m/s]
D_T_S = 5.0 / 3.6 # target speed sampling length [m/s]
N_S_SAMPLE = 1 # sampling number of target speed
ROBOT_RADIUS = 2.0 # robot radius [m]
# cost weights
K_J = 0.1
K_T = 0.1
K_D = 1.0
K_LAT = 1.0
K_LON = 1.0
show_animation = True
class QuarticPolynomial:
def __init__(self, xs, vxs, axs, vxe, axe, time):
# calc coefficient of quartic polynomial
self.a0 = xs
self.a1 = vxs
self.a2 = axs / 2.0
A = np.array([[3 * time ** 2, 4 * time ** 3],
[6 * time, 12 * time ** 2]])
b = np.array([vxe - self.a1 - 2 * self.a2 * time,
axe - 2 * self.a2])
x = np.linalg.solve(A, b)
self.a3 = x[0]
self.a4 = x[1]
def calc_point(self, t):
xt = self.a0 + self.a1 * t + self.a2 * t ** 2 + \
self.a3 * t ** 3 + self.a4 * t ** 4
return xt
def calc_first_derivative(self, t):
xt = self.a1 + 2 * self.a2 * t + \
3 * self.a3 * t ** 2 + 4 * self.a4 * t ** 3
return xt
def calc_second_derivative(self, t):
xt = 2 * self.a2 + 6 * self.a3 * t + 12 * self.a4 * t ** 2
return xt
def calc_third_derivative(self, t):
xt = 6 * self.a3 + 24 * self.a4 * t
return xt
class FrenetPath:
def __init__(self):
self.t = []
self.d = []
self.d_d = []
self.d_dd = []
self.d_ddd = []
self.s = []
self.s_d = []
self.s_dd = []
self.s_ddd = []
self.cd = 0.0
self.cv = 0.0
self.cf = 0.0
self.x = []
self.y = []
self.yaw = []
self.ds = []
self.c = []
def calc_frenet_paths(c_speed, c_accel, c_d, c_d_d, c_d_dd, s0):
frenet_paths = []
# generate path to each offset goal
for di in np.arange(-MAX_ROAD_WIDTH, MAX_ROAD_WIDTH, D_ROAD_W):
# Lateral motion planning
for Ti in np.arange(MIN_T, MAX_T, DT):
fp = FrenetPath()
# lat_qp = quintic_polynomial(c_d, c_d_d, c_d_dd, di, 0.0, 0.0, Ti)
lat_qp = QuinticPolynomial(c_d, c_d_d, c_d_dd, di, 0.0, 0.0, Ti)
fp.t = [t for t in np.arange(0.0, Ti, DT)]
fp.d = [lat_qp.calc_point(t) for t in fp.t]
fp.d_d = [lat_qp.calc_first_derivative(t) for t in fp.t]
fp.d_dd = [lat_qp.calc_second_derivative(t) for t in fp.t]
fp.d_ddd = [lat_qp.calc_third_derivative(t) for t in fp.t]
# Longitudinal motion planning (Velocity keeping)
for tv in np.arange(TARGET_SPEED - D_T_S * N_S_SAMPLE,
TARGET_SPEED + D_T_S * N_S_SAMPLE, D_T_S):
tfp = copy.deepcopy(fp)
lon_qp = QuarticPolynomial(s0, c_speed, c_accel, tv, 0.0, Ti)
tfp.s = [lon_qp.calc_point(t) for t in fp.t]
tfp.s_d = [lon_qp.calc_first_derivative(t) for t in fp.t]
tfp.s_dd = [lon_qp.calc_second_derivative(t) for t in fp.t]
tfp.s_ddd = [lon_qp.calc_third_derivative(t) for t in fp.t]
Jp = sum(np.power(tfp.d_ddd, 2)) # square of jerk
Js = sum(np.power(tfp.s_ddd, 2)) # square of jerk
# square of diff from target speed
ds = (TARGET_SPEED - tfp.s_d[-1]) ** 2
tfp.cd = K_J * Jp + K_T * Ti + K_D * tfp.d[-1] ** 2
tfp.cv = K_J * Js + K_T * Ti + K_D * ds
tfp.cf = K_LAT * tfp.cd + K_LON * tfp.cv
frenet_paths.append(tfp)
return frenet_paths
def calc_global_paths(fplist, csp):
for fp in fplist:
# calc global positions
for i in range(len(fp.s)):
ix, iy = csp.calc_position(fp.s[i])
if ix is None:
break
i_yaw = csp.calc_yaw(fp.s[i])
di = fp.d[i]
fx = ix + di * math.cos(i_yaw + math.pi / 2.0)
fy = iy + di * math.sin(i_yaw + math.pi / 2.0)
fp.x.append(fx)
fp.y.append(fy)
# calc yaw and ds
for i in range(len(fp.x) - 1):
dx = fp.x[i + 1] - fp.x[i]
dy = fp.y[i + 1] - fp.y[i]
fp.yaw.append(math.atan2(dy, dx))
fp.ds.append(math.hypot(dx, dy))
fp.yaw.append(fp.yaw[-1])
fp.ds.append(fp.ds[-1])
# calc curvature
for i in range(len(fp.yaw) - 1):
fp.c.append((fp.yaw[i + 1] - fp.yaw[i]) / fp.ds[i])
return fplist
def check_collision(fp, ob):
for i in range(len(ob[:, 0])):
d = [((ix - ob[i, 0]) ** 2 + (iy - ob[i, 1]) ** 2)
for (ix, iy) in zip(fp.x, fp.y)]
collision = any([di <= ROBOT_RADIUS ** 2 for di in d])
if collision:
return False
return True
def check_paths(fplist, ob):
ok_ind = []
for i, _ in enumerate(fplist):
if any([v > MAX_SPEED for v in fplist[i].s_d]): # Max speed check
continue
elif any([abs(a) > MAX_ACCEL for a in
fplist[i].s_dd]): # Max accel check
continue
elif any([abs(c) > MAX_CURVATURE for c in
fplist[i].c]): # Max curvature check
continue
elif not check_collision(fplist[i], ob):
continue
ok_ind.append(i)
return [fplist[i] for i in ok_ind]
def frenet_optimal_planning(csp, s0, c_speed, c_accel, c_d, c_d_d, c_d_dd, ob):
fplist = calc_frenet_paths(c_speed, c_accel, c_d, c_d_d, c_d_dd, s0)
fplist = calc_global_paths(fplist, csp)
fplist = check_paths(fplist, ob)
# find minimum cost path
min_cost = float("inf")
best_path = None
for fp in fplist:
if min_cost >= fp.cf:
min_cost = fp.cf
best_path = fp
return best_path
def generate_target_course(x, y):
csp = cubic_spline_planner.CubicSpline2D(x, y)
s = np.arange(0, csp.s[-1], 0.1)
rx, ry, ryaw, rk = [], [], [], []
for i_s in s:
ix, iy = csp.calc_position(i_s)
rx.append(ix)
ry.append(iy)
ryaw.append(csp.calc_yaw(i_s))
rk.append(csp.calc_curvature(i_s))
return rx, ry, ryaw, rk, csp
def main():
print(__file__ + " start!!")
# way points
wx = [0.0, 10.0, 20.5, 35.0, 70.5]
wy = [0.0, -6.0, 5.0, 6.5, 0.0]
# obstacle lists
ob = np.array([[20.0, 10.0],
[30.0, 6.0],
[30.0, 8.0],
[35.0, 8.0],
[50.0, 3.0]
])
tx, ty, tyaw, tc, csp = generate_target_course(wx, wy)
# initial state
c_speed = 10.0 / 3.6 # current speed [m/s]
c_accel = 0.0 # current acceleration [m/ss]
c_d = 2.0 # current lateral position [m]
c_d_d = 0.0 # current lateral speed [m/s]
c_d_dd = 0.0 # current lateral acceleration [m/s]
s0 = 0.0 # current course position
area = 20.0 # animation area length [m]
for i in range(SIM_LOOP):
path = frenet_optimal_planning(
csp, s0, c_speed, c_accel, c_d, c_d_d, c_d_dd, ob)
s0 = path.s[1]
c_d = path.d[1]
c_d_d = path.d_d[1]
c_d_dd = path.d_dd[1]
c_speed = path.s_d[1]
c_accel = path.s_dd[1]
if np.hypot(path.x[1] - tx[-1], path.y[1] - ty[-1]) <= 1.0:
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])
plt.plot(tx, ty)
plt.plot(ob[:, 0], ob[:, 1], "xk")
plt.plot(path.x[1:], path.y[1:], "-or")
plt.plot(path.x[1], path.y[1], "vc")
plt.xlim(path.x[1] - area, path.x[1] + area)
plt.ylim(path.y[1] - area, path.y[1] + area)
plt.title("v[km/h]:" + str(c_speed * 3.6)[0:4])
plt.grid(True)
plt.pause(0.0001)
print("Finish")
if show_animation: # pragma: no cover
plt.grid(True)
plt.pause(0.0001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/FrenetOptimalTrajectory/frenet_optimal_trajectory.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,872 |
```python
"""
Grid based sweep planner
author: Atsushi Sakai
"""
import math
from enum import IntEnum
import numpy as np
import matplotlib.pyplot as plt
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent.parent))
from utils.angle import rot_mat_2d
from Mapping.grid_map_lib.grid_map_lib import GridMap, FloatGrid
do_animation = True
class SweepSearcher:
class SweepDirection(IntEnum):
UP = 1
DOWN = -1
class MovingDirection(IntEnum):
RIGHT = 1
LEFT = -1
def __init__(self,
moving_direction, sweep_direction, x_inds_goal_y, goal_y):
self.moving_direction = moving_direction
self.sweep_direction = sweep_direction
self.turing_window = []
self.update_turning_window()
self.x_indexes_goal_y = x_inds_goal_y
self.goal_y = goal_y
def move_target_grid(self, c_x_index, c_y_index, grid_map):
n_x_index = self.moving_direction + c_x_index
n_y_index = c_y_index
# found safe grid
if not self.check_occupied(n_x_index, n_y_index, grid_map):
return n_x_index, n_y_index
else: # occupied
next_c_x_index, next_c_y_index = self.find_safe_turning_grid(
c_x_index, c_y_index, grid_map)
if (next_c_x_index is None) and (next_c_y_index is None):
# moving backward
next_c_x_index = -self.moving_direction + c_x_index
next_c_y_index = c_y_index
if self.check_occupied(next_c_x_index, next_c_y_index, grid_map, FloatGrid(1.0)):
# moved backward, but the grid is occupied by obstacle
return None, None
else:
# keep moving until end
while not self.check_occupied(next_c_x_index + self.moving_direction, next_c_y_index, grid_map):
next_c_x_index += self.moving_direction
self.swap_moving_direction()
return next_c_x_index, next_c_y_index
@staticmethod
def check_occupied(c_x_index, c_y_index, grid_map, occupied_val=FloatGrid(0.5)):
return grid_map.check_occupied_from_xy_index(c_x_index, c_y_index, occupied_val)
def find_safe_turning_grid(self, c_x_index, c_y_index, grid_map):
for (d_x_ind, d_y_ind) in self.turing_window:
next_x_ind = d_x_ind + c_x_index
next_y_ind = d_y_ind + c_y_index
# found safe grid
if not self.check_occupied(next_x_ind, next_y_ind, grid_map):
return next_x_ind, next_y_ind
return None, None
def is_search_done(self, grid_map):
for ix in self.x_indexes_goal_y:
if not self.check_occupied(ix, self.goal_y, grid_map):
return False
# all lower grid is occupied
return True
def update_turning_window(self):
# turning window definition
# robot can move grid based on it.
self.turing_window = [
(self.moving_direction, 0.0),
(self.moving_direction, self.sweep_direction),
(0, self.sweep_direction),
(-self.moving_direction, self.sweep_direction),
]
def swap_moving_direction(self):
self.moving_direction *= -1
self.update_turning_window()
def search_start_grid(self, grid_map):
x_inds = []
y_ind = 0
if self.sweep_direction == self.SweepDirection.DOWN:
x_inds, y_ind = search_free_grid_index_at_edge_y(
grid_map, from_upper=True)
elif self.sweep_direction == self.SweepDirection.UP:
x_inds, y_ind = search_free_grid_index_at_edge_y(
grid_map, from_upper=False)
if self.moving_direction == self.MovingDirection.RIGHT:
return min(x_inds), y_ind
elif self.moving_direction == self.MovingDirection.LEFT:
return max(x_inds), y_ind
raise ValueError("self.moving direction is invalid ")
def find_sweep_direction_and_start_position(ox, oy):
# find sweep_direction
max_dist = 0.0
vec = [0.0, 0.0]
sweep_start_pos = [0.0, 0.0]
for i in range(len(ox) - 1):
dx = ox[i + 1] - ox[i]
dy = oy[i + 1] - oy[i]
d = np.hypot(dx, dy)
if d > max_dist:
max_dist = d
vec = [dx, dy]
sweep_start_pos = [ox[i], oy[i]]
return vec, sweep_start_pos
def convert_grid_coordinate(ox, oy, sweep_vec, sweep_start_position):
tx = [ix - sweep_start_position[0] for ix in ox]
ty = [iy - sweep_start_position[1] for iy in oy]
th = math.atan2(sweep_vec[1], sweep_vec[0])
converted_xy = np.stack([tx, ty]).T @ rot_mat_2d(th)
return converted_xy[:, 0], converted_xy[:, 1]
def convert_global_coordinate(x, y, sweep_vec, sweep_start_position):
th = math.atan2(sweep_vec[1], sweep_vec[0])
converted_xy = np.stack([x, y]).T @ rot_mat_2d(-th)
rx = [ix + sweep_start_position[0] for ix in converted_xy[:, 0]]
ry = [iy + sweep_start_position[1] for iy in converted_xy[:, 1]]
return rx, ry
def search_free_grid_index_at_edge_y(grid_map, from_upper=False):
y_index = None
x_indexes = []
if from_upper:
x_range = range(grid_map.height)[::-1]
y_range = range(grid_map.width)[::-1]
else:
x_range = range(grid_map.height)
y_range = range(grid_map.width)
for iy in x_range:
for ix in y_range:
if not SweepSearcher.check_occupied(ix, iy, grid_map):
y_index = iy
x_indexes.append(ix)
if y_index:
break
return x_indexes, y_index
def setup_grid_map(ox, oy, resolution, sweep_direction, offset_grid=10):
width = math.ceil((max(ox) - min(ox)) / resolution) + offset_grid
height = math.ceil((max(oy) - min(oy)) / resolution) + offset_grid
center_x = (np.max(ox) + np.min(ox)) / 2.0
center_y = (np.max(oy) + np.min(oy)) / 2.0
grid_map = GridMap(width, height, resolution, center_x, center_y)
grid_map.print_grid_map_info()
grid_map.set_value_from_polygon(ox, oy, FloatGrid(1.0), inside=False)
grid_map.expand_grid()
x_inds_goal_y = []
goal_y = 0
if sweep_direction == SweepSearcher.SweepDirection.UP:
x_inds_goal_y, goal_y = search_free_grid_index_at_edge_y(
grid_map, from_upper=True)
elif sweep_direction == SweepSearcher.SweepDirection.DOWN:
x_inds_goal_y, goal_y = search_free_grid_index_at_edge_y(
grid_map, from_upper=False)
return grid_map, x_inds_goal_y, goal_y
def sweep_path_search(sweep_searcher, grid_map, grid_search_animation=False):
# search start grid
c_x_index, c_y_index = sweep_searcher.search_start_grid(grid_map)
if not grid_map.set_value_from_xy_index(c_x_index, c_y_index, FloatGrid(0.5)):
print("Cannot find start grid")
return [], []
x, y = grid_map.calc_grid_central_xy_position_from_xy_index(c_x_index,
c_y_index)
px, py = [x], [y]
fig, ax = None, None
if grid_search_animation:
fig, ax = plt.subplots()
# for stopping simulation with the esc key.
fig.canvas.mpl_connect(
'key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
while True:
c_x_index, c_y_index = sweep_searcher.move_target_grid(c_x_index,
c_y_index,
grid_map)
if sweep_searcher.is_search_done(grid_map) or (
c_x_index is None or c_y_index is None):
print("Done")
break
x, y = grid_map.calc_grid_central_xy_position_from_xy_index(
c_x_index, c_y_index)
px.append(x)
py.append(y)
grid_map.set_value_from_xy_index(c_x_index, c_y_index, FloatGrid(0.5))
if grid_search_animation:
grid_map.plot_grid_map(ax=ax)
plt.pause(1.0)
return px, py
def planning(ox, oy, resolution,
moving_direction=SweepSearcher.MovingDirection.RIGHT,
sweeping_direction=SweepSearcher.SweepDirection.UP,
):
sweep_vec, sweep_start_position = find_sweep_direction_and_start_position(
ox, oy)
rox, roy = convert_grid_coordinate(ox, oy, sweep_vec,
sweep_start_position)
grid_map, x_inds_goal_y, goal_y = setup_grid_map(rox, roy, resolution,
sweeping_direction)
sweep_searcher = SweepSearcher(moving_direction, sweeping_direction,
x_inds_goal_y, goal_y)
px, py = sweep_path_search(sweep_searcher, grid_map)
rx, ry = convert_global_coordinate(px, py, sweep_vec,
sweep_start_position)
print("Path length:", len(rx))
return rx, ry
def planning_animation(ox, oy, resolution): # pragma: no cover
px, py = planning(ox, oy, resolution)
# animation
if do_animation:
for ipx, ipy in zip(px, py):
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(ox, oy, "-xb")
plt.plot(px, py, "-r")
plt.plot(ipx, ipy, "or")
plt.axis("equal")
plt.grid(True)
plt.pause(0.1)
plt.cla()
plt.plot(ox, oy, "-xb")
plt.plot(px, py, "-r")
plt.axis("equal")
plt.grid(True)
plt.pause(0.1)
plt.close()
def main(): # pragma: no cover
print("start!!")
ox = [0.0, 20.0, 50.0, 100.0, 130.0, 40.0, 0.0]
oy = [0.0, -20.0, 0.0, 30.0, 60.0, 80.0, 0.0]
resolution = 5.0
planning_animation(ox, oy, resolution)
ox = [0.0, 50.0, 50.0, 0.0, 0.0]
oy = [0.0, 0.0, 30.0, 30.0, 0.0]
resolution = 1.3
planning_animation(ox, oy, resolution)
ox = [0.0, 20.0, 50.0, 200.0, 130.0, 40.0, 0.0]
oy = [0.0, -80.0, 0.0, 30.0, 60.0, 80.0, 0.0]
resolution = 5.0
planning_animation(ox, oy, resolution)
if do_animation:
plt.show()
print("done!!")
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/GridBasedSweepCPP/grid_based_sweep_coverage_path_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,699 |
```python
"""
D* grid planning
author: Nirnay Roy
See Wikipedia article (path_to_url
"""
import math
from sys import maxsize
import matplotlib.pyplot as plt
show_animation = True
class State:
def __init__(self, x, y):
self.x = x
self.y = y
self.parent = None
self.state = "."
self.t = "new" # tag for state
self.h = 0
self.k = 0
def cost(self, state):
if self.state == "#" or state.state == "#":
return maxsize
return math.sqrt(math.pow((self.x - state.x), 2) +
math.pow((self.y - state.y), 2))
def set_state(self, state):
"""
.: new
#: obstacle
e: oparent of current state
*: closed state
s: current state
"""
if state not in ["s", ".", "#", "e", "*"]:
return
self.state = state
class Map:
def __init__(self, row, col):
self.row = row
self.col = col
self.map = self.init_map()
def init_map(self):
map_list = []
for i in range(self.row):
tmp = []
for j in range(self.col):
tmp.append(State(i, j))
map_list.append(tmp)
return map_list
def get_neighbors(self, state):
state_list = []
for i in [-1, 0, 1]:
for j in [-1, 0, 1]:
if i == 0 and j == 0:
continue
if state.x + i < 0 or state.x + i >= self.row:
continue
if state.y + j < 0 or state.y + j >= self.col:
continue
state_list.append(self.map[state.x + i][state.y + j])
return state_list
def set_obstacle(self, point_list):
for x, y in point_list:
if x < 0 or x >= self.row or y < 0 or y >= self.col:
continue
self.map[x][y].set_state("#")
class Dstar:
def __init__(self, maps):
self.map = maps
self.open_list = set()
def process_state(self):
x = self.min_state()
if x is None:
return -1
k_old = self.get_kmin()
self.remove(x)
if k_old < x.h:
for y in self.map.get_neighbors(x):
if y.h <= k_old and x.h > y.h + x.cost(y):
x.parent = y
x.h = y.h + x.cost(y)
if k_old == x.h:
for y in self.map.get_neighbors(x):
if y.t == "new" or y.parent == x and y.h != x.h + x.cost(y) \
or y.parent != x and y.h > x.h + x.cost(y):
y.parent = x
self.insert(y, x.h + x.cost(y))
else:
for y in self.map.get_neighbors(x):
if y.t == "new" or y.parent == x and y.h != x.h + x.cost(y):
y.parent = x
self.insert(y, x.h + x.cost(y))
else:
if y.parent != x and y.h > x.h + x.cost(y):
self.insert(x, x.h)
else:
if y.parent != x and x.h > y.h + x.cost(y) \
and y.t == "close" and y.h > k_old:
self.insert(y, y.h)
return self.get_kmin()
def min_state(self):
if not self.open_list:
return None
min_state = min(self.open_list, key=lambda x: x.k)
return min_state
def get_kmin(self):
if not self.open_list:
return -1
k_min = min([x.k for x in self.open_list])
return k_min
def insert(self, state, h_new):
if state.t == "new":
state.k = h_new
elif state.t == "open":
state.k = min(state.k, h_new)
elif state.t == "close":
state.k = min(state.h, h_new)
state.h = h_new
state.t = "open"
self.open_list.add(state)
def remove(self, state):
if state.t == "open":
state.t = "close"
self.open_list.remove(state)
def modify_cost(self, x):
if x.t == "close":
self.insert(x, x.parent.h + x.cost(x.parent))
def run(self, start, end):
rx = []
ry = []
self.insert(end, 0.0)
while True:
self.process_state()
if start.t == "close":
break
start.set_state("s")
s = start
s = s.parent
s.set_state("e")
tmp = start
AddNewObstacle(self.map) # add new obstacle after the first search finished
while tmp != end:
tmp.set_state("*")
rx.append(tmp.x)
ry.append(tmp.y)
if show_animation:
plt.plot(rx, ry, "-r")
plt.pause(0.01)
if tmp.parent.state == "#":
self.modify(tmp)
continue
tmp = tmp.parent
tmp.set_state("e")
return rx, ry
def modify(self, state):
self.modify_cost(state)
while True:
k_min = self.process_state()
if k_min >= state.h:
break
def AddNewObstacle(map:Map):
ox, oy = [], []
for i in range(5, 21):
ox.append(i)
oy.append(40)
map.set_obstacle([(i, j) for i, j in zip(ox, oy)])
if show_animation:
plt.pause(0.001)
plt.plot(ox, oy, ".g")
def main():
m = Map(100, 100)
ox, oy = [], []
for i in range(-10, 60):
ox.append(i)
oy.append(-10)
for i in range(-10, 60):
ox.append(60)
oy.append(i)
for i in range(-10, 61):
ox.append(i)
oy.append(60)
for i in range(-10, 61):
ox.append(-10)
oy.append(i)
for i in range(-10, 40):
ox.append(20)
oy.append(i)
for i in range(0, 40):
ox.append(40)
oy.append(60 - i)
m.set_obstacle([(i, j) for i, j in zip(ox, oy)])
start = [10, 10]
goal = [50, 50]
if show_animation:
plt.plot(ox, oy, ".k")
plt.plot(start[0], start[1], "og")
plt.plot(goal[0], goal[1], "xb")
plt.axis("equal")
start = m.map[start[0]][start[1]]
end = m.map[goal[0]][goal[1]]
dstar = Dstar(m)
rx, ry = dstar.run(start, end)
if show_animation:
plt.plot(rx, ry, "-r")
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/DStar/dstar.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,650 |
```python
"""
State lattice planner with model predictive trajectory generator
author: Atsushi Sakai (@Atsushi_twi)
- plookuptable.csv is generated with this script:
path_to_url
/ModelPredictiveTrajectoryGenerator/lookup_table_generator.py
Ref:
- State Space Sampling of Feasible Motions for High-Performance Mobile Robot
Navigation in Complex Environments
path_to_url
&type=pdf
"""
import sys
import os
from matplotlib import pyplot as plt
import numpy as np
import math
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
import ModelPredictiveTrajectoryGenerator.trajectory_generator as planner
import ModelPredictiveTrajectoryGenerator.motion_model as motion_model
TABLE_PATH = os.path.dirname(os.path.abspath(__file__)) + "/lookup_table.csv"
show_animation = True
def search_nearest_one_from_lookup_table(t_x, t_y, t_yaw, lookup_table):
mind = float("inf")
minid = -1
for (i, table) in enumerate(lookup_table):
dx = t_x - table[0]
dy = t_y - table[1]
dyaw = t_yaw - table[2]
d = math.sqrt(dx ** 2 + dy ** 2 + dyaw ** 2)
if d <= mind:
minid = i
mind = d
return lookup_table[minid]
def get_lookup_table(table_path):
return np.loadtxt(table_path, delimiter=',', skiprows=1)
def generate_path(target_states, k0):
# x, y, yaw, s, km, kf
lookup_table = get_lookup_table(TABLE_PATH)
result = []
for state in target_states:
bestp = search_nearest_one_from_lookup_table(
state[0], state[1], state[2], lookup_table)
target = motion_model.State(x=state[0], y=state[1], yaw=state[2])
init_p = np.array(
[np.hypot(state[0], state[1]), bestp[4], bestp[5]]).reshape(3, 1)
x, y, yaw, p = planner.optimize_trajectory(target, k0, init_p)
if x is not None:
print("find good path")
result.append(
[x[-1], y[-1], yaw[-1], float(p[0, 0]), float(p[1, 0]), float(p[2, 0])])
print("finish path generation")
return result
def calc_uniform_polar_states(nxy, nh, d, a_min, a_max, p_min, p_max):
"""
Parameters
----------
nxy :
number of position sampling
nh :
number of heading sampleing
d :
distance of terminal state
a_min :
position sampling min angle
a_max :
position sampling max angle
p_min :
heading sampling min angle
p_max :
heading sampling max angle
Returns
-------
"""
angle_samples = [i / (nxy - 1) for i in range(nxy)]
states = sample_states(angle_samples, a_min, a_max, d, p_max, p_min, nh)
return states
def calc_biased_polar_states(goal_angle, ns, nxy, nh, d, a_min, a_max, p_min, p_max):
"""
calc biased state
:param goal_angle: goal orientation for biased sampling
:param ns: number of biased sampling
:param nxy: number of position sampling
:param nxy: number of position sampling
:param nh: number of heading sampleing
:param d: distance of terminal state
:param a_min: position sampling min angle
:param a_max: position sampling max angle
:param p_min: heading sampling min angle
:param p_max: heading sampling max angle
:return: states list
"""
asi = [a_min + (a_max - a_min) * i / (ns - 1) for i in range(ns - 1)]
cnav = [math.pi - abs(i - goal_angle) for i in asi]
cnav_sum = sum(cnav)
cnav_max = max(cnav)
# normalize
cnav = [(cnav_max - cnav[i]) / (cnav_max * ns - cnav_sum)
for i in range(ns - 1)]
csumnav = np.cumsum(cnav)
di = []
li = 0
for i in range(nxy):
for ii in range(li, ns - 1):
if ii / ns >= i / (nxy - 1):
di.append(csumnav[ii])
li = ii - 1
break
states = sample_states(di, a_min, a_max, d, p_max, p_min, nh)
return states
def calc_lane_states(l_center, l_heading, l_width, v_width, d, nxy):
"""
calc lane states
:param l_center: lane lateral position
:param l_heading: lane heading
:param l_width: lane width
:param v_width: vehicle width
:param d: longitudinal position
:param nxy: sampling number
:return: state list
"""
xc = d
yc = l_center
states = []
for i in range(nxy):
delta = -0.5 * (l_width - v_width) + \
(l_width - v_width) * i / (nxy - 1)
xf = xc - delta * math.sin(l_heading)
yf = yc + delta * math.cos(l_heading)
yawf = l_heading
states.append([xf, yf, yawf])
return states
def sample_states(angle_samples, a_min, a_max, d, p_max, p_min, nh):
states = []
for i in angle_samples:
a = a_min + (a_max - a_min) * i
for j in range(nh):
xf = d * math.cos(a)
yf = d * math.sin(a)
if nh == 1:
yawf = (p_max - p_min) / 2 + a
else:
yawf = p_min + (p_max - p_min) * j / (nh - 1) + a
states.append([xf, yf, yawf])
return states
def uniform_terminal_state_sampling_test1():
k0 = 0.0
nxy = 5
nh = 3
d = 20
a_min = - np.deg2rad(45.0)
a_max = np.deg2rad(45.0)
p_min = - np.deg2rad(45.0)
p_max = np.deg2rad(45.0)
states = calc_uniform_polar_states(nxy, nh, d, a_min, a_max, p_min, p_max)
result = generate_path(states, k0)
for table in result:
xc, yc, yawc = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
if show_animation:
plt.plot(xc, yc, "-r")
if show_animation:
plt.grid(True)
plt.axis("equal")
plt.show()
print("Done")
def uniform_terminal_state_sampling_test2():
k0 = 0.1
nxy = 6
nh = 3
d = 20
a_min = - np.deg2rad(-10.0)
a_max = np.deg2rad(45.0)
p_min = - np.deg2rad(20.0)
p_max = np.deg2rad(20.0)
states = calc_uniform_polar_states(nxy, nh, d, a_min, a_max, p_min, p_max)
result = generate_path(states, k0)
for table in result:
xc, yc, yawc = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
if show_animation:
plt.plot(xc, yc, "-r")
if show_animation:
plt.grid(True)
plt.axis("equal")
plt.show()
print("Done")
def biased_terminal_state_sampling_test1():
k0 = 0.0
nxy = 30
nh = 2
d = 20
a_min = np.deg2rad(-45.0)
a_max = np.deg2rad(45.0)
p_min = - np.deg2rad(20.0)
p_max = np.deg2rad(20.0)
ns = 100
goal_angle = np.deg2rad(0.0)
states = calc_biased_polar_states(
goal_angle, ns, nxy, nh, d, a_min, a_max, p_min, p_max)
result = generate_path(states, k0)
for table in result:
xc, yc, yawc = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
if show_animation:
plt.plot(xc, yc, "-r")
if show_animation:
plt.grid(True)
plt.axis("equal")
plt.show()
def biased_terminal_state_sampling_test2():
k0 = 0.0
nxy = 30
nh = 1
d = 20
a_min = np.deg2rad(0.0)
a_max = np.deg2rad(45.0)
p_min = - np.deg2rad(20.0)
p_max = np.deg2rad(20.0)
ns = 100
goal_angle = np.deg2rad(30.0)
states = calc_biased_polar_states(
goal_angle, ns, nxy, nh, d, a_min, a_max, p_min, p_max)
result = generate_path(states, k0)
for table in result:
xc, yc, yawc = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
if show_animation:
plt.plot(xc, yc, "-r")
if show_animation:
plt.grid(True)
plt.axis("equal")
plt.show()
def lane_state_sampling_test1():
k0 = 0.0
l_center = 10.0
l_heading = np.deg2rad(0.0)
l_width = 3.0
v_width = 1.0
d = 10
nxy = 5
states = calc_lane_states(l_center, l_heading, l_width, v_width, d, nxy)
result = generate_path(states, k0)
if show_animation:
plt.close("all")
for table in result:
x_c, y_c, yaw_c = motion_model.generate_trajectory(
table[3], table[4], table[5], k0)
if show_animation:
plt.plot(x_c, y_c, "-r")
if show_animation:
plt.grid(True)
plt.axis("equal")
plt.show()
def main():
planner.show_animation = show_animation
uniform_terminal_state_sampling_test1()
uniform_terminal_state_sampling_test2()
biased_terminal_state_sampling_test1()
biased_terminal_state_sampling_test2()
lane_state_sampling_test1()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/StateLatticePlanner/state_lattice_planner.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,512 |
```python
"""
Mobile robot motion planning sample with Dynamic Window Approach
author: Atsushi Sakai (@Atsushi_twi), Gktu Karakal
"""
import math
from enum import Enum
import matplotlib.pyplot as plt
import numpy as np
show_animation = True
def dwa_control(x, config, goal, ob):
"""
Dynamic Window Approach control
"""
dw = calc_dynamic_window(x, config)
u, trajectory = calc_control_and_trajectory(x, dw, config, goal, ob)
return u, trajectory
class RobotType(Enum):
circle = 0
rectangle = 1
class Config:
"""
simulation parameter class
"""
def __init__(self):
# robot parameter
self.max_speed = 1.0 # [m/s]
self.min_speed = -0.5 # [m/s]
self.max_yaw_rate = 40.0 * math.pi / 180.0 # [rad/s]
self.max_accel = 0.2 # [m/ss]
self.max_delta_yaw_rate = 40.0 * math.pi / 180.0 # [rad/ss]
self.v_resolution = 0.01 # [m/s]
self.yaw_rate_resolution = 0.1 * math.pi / 180.0 # [rad/s]
self.dt = 0.1 # [s] Time tick for motion prediction
self.predict_time = 3.0 # [s]
self.to_goal_cost_gain = 0.15
self.speed_cost_gain = 1.0
self.obstacle_cost_gain = 1.0
self.robot_stuck_flag_cons = 0.001 # constant to prevent robot stucked
self.robot_type = RobotType.circle
# if robot_type == RobotType.circle
# Also used to check if goal is reached in both types
self.robot_radius = 1.0 # [m] for collision check
# if robot_type == RobotType.rectangle
self.robot_width = 0.5 # [m] for collision check
self.robot_length = 1.2 # [m] for collision check
# obstacles [x(m) y(m), ....]
self.ob = np.array([[-1, -1],
[0, 2],
[4.0, 2.0],
[5.0, 4.0],
[5.0, 5.0],
[5.0, 6.0],
[5.0, 9.0],
[8.0, 9.0],
[7.0, 9.0],
[8.0, 10.0],
[9.0, 11.0],
[12.0, 13.0],
[12.0, 12.0],
[15.0, 15.0],
[13.0, 13.0]
])
@property
def robot_type(self):
return self._robot_type
@robot_type.setter
def robot_type(self, value):
if not isinstance(value, RobotType):
raise TypeError("robot_type must be an instance of RobotType")
self._robot_type = value
config = Config()
def motion(x, u, dt):
"""
motion model
"""
x[2] += u[1] * dt
x[0] += u[0] * math.cos(x[2]) * dt
x[1] += u[0] * math.sin(x[2]) * dt
x[3] = u[0]
x[4] = u[1]
return x
def calc_dynamic_window(x, config):
"""
calculation dynamic window based on current state x
"""
# Dynamic window from robot specification
Vs = [config.min_speed, config.max_speed,
-config.max_yaw_rate, config.max_yaw_rate]
# Dynamic window from motion model
Vd = [x[3] - config.max_accel * config.dt,
x[3] + config.max_accel * config.dt,
x[4] - config.max_delta_yaw_rate * config.dt,
x[4] + config.max_delta_yaw_rate * config.dt]
# [v_min, v_max, yaw_rate_min, yaw_rate_max]
dw = [max(Vs[0], Vd[0]), min(Vs[1], Vd[1]),
max(Vs[2], Vd[2]), min(Vs[3], Vd[3])]
return dw
def predict_trajectory(x_init, v, y, config):
"""
predict trajectory with an input
"""
x = np.array(x_init)
trajectory = np.array(x)
time = 0
while time <= config.predict_time:
x = motion(x, [v, y], config.dt)
trajectory = np.vstack((trajectory, x))
time += config.dt
return trajectory
def calc_control_and_trajectory(x, dw, config, goal, ob):
"""
calculation final input with dynamic window
"""
x_init = x[:]
min_cost = float("inf")
best_u = [0.0, 0.0]
best_trajectory = np.array([x])
# evaluate all trajectory with sampled input in dynamic window
for v in np.arange(dw[0], dw[1], config.v_resolution):
for y in np.arange(dw[2], dw[3], config.yaw_rate_resolution):
trajectory = predict_trajectory(x_init, v, y, config)
# calc cost
to_goal_cost = config.to_goal_cost_gain * calc_to_goal_cost(trajectory, goal)
speed_cost = config.speed_cost_gain * (config.max_speed - trajectory[-1, 3])
ob_cost = config.obstacle_cost_gain * calc_obstacle_cost(trajectory, ob, config)
final_cost = to_goal_cost + speed_cost + ob_cost
# search minimum trajectory
if min_cost >= final_cost:
min_cost = final_cost
best_u = [v, y]
best_trajectory = trajectory
if abs(best_u[0]) < config.robot_stuck_flag_cons \
and abs(x[3]) < config.robot_stuck_flag_cons:
# to ensure the robot do not get stuck in
# best v=0 m/s (in front of an obstacle) and
# best omega=0 rad/s (heading to the goal with
# angle difference of 0)
best_u[1] = -config.max_delta_yaw_rate
return best_u, best_trajectory
def calc_obstacle_cost(trajectory, ob, config):
"""
calc obstacle cost inf: collision
"""
ox = ob[:, 0]
oy = ob[:, 1]
dx = trajectory[:, 0] - ox[:, None]
dy = trajectory[:, 1] - oy[:, None]
r = np.hypot(dx, dy)
if config.robot_type == RobotType.rectangle:
yaw = trajectory[:, 2]
rot = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])
rot = np.transpose(rot, [2, 0, 1])
local_ob = ob[:, None] - trajectory[:, 0:2]
local_ob = local_ob.reshape(-1, local_ob.shape[-1])
local_ob = np.array([local_ob @ x for x in rot])
local_ob = local_ob.reshape(-1, local_ob.shape[-1])
upper_check = local_ob[:, 0] <= config.robot_length / 2
right_check = local_ob[:, 1] <= config.robot_width / 2
bottom_check = local_ob[:, 0] >= -config.robot_length / 2
left_check = local_ob[:, 1] >= -config.robot_width / 2
if (np.logical_and(np.logical_and(upper_check, right_check),
np.logical_and(bottom_check, left_check))).any():
return float("Inf")
elif config.robot_type == RobotType.circle:
if np.array(r <= config.robot_radius).any():
return float("Inf")
min_r = np.min(r)
return 1.0 / min_r # OK
def calc_to_goal_cost(trajectory, goal):
"""
calc to goal cost with angle difference
"""
dx = goal[0] - trajectory[-1, 0]
dy = goal[1] - trajectory[-1, 1]
error_angle = math.atan2(dy, dx)
cost_angle = error_angle - trajectory[-1, 2]
cost = abs(math.atan2(math.sin(cost_angle), math.cos(cost_angle)))
return cost
def plot_arrow(x, y, yaw, length=0.5, width=0.1): # pragma: no cover
plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
head_length=width, head_width=width)
plt.plot(x, y)
def plot_robot(x, y, yaw, config): # pragma: no cover
if config.robot_type == RobotType.rectangle:
outline = np.array([[-config.robot_length / 2, config.robot_length / 2,
(config.robot_length / 2), -config.robot_length / 2,
-config.robot_length / 2],
[config.robot_width / 2, config.robot_width / 2,
- config.robot_width / 2, -config.robot_width / 2,
config.robot_width / 2]])
Rot1 = np.array([[math.cos(yaw), math.sin(yaw)],
[-math.sin(yaw), math.cos(yaw)]])
outline = (outline.T.dot(Rot1)).T
outline[0, :] += x
outline[1, :] += y
plt.plot(np.array(outline[0, :]).flatten(),
np.array(outline[1, :]).flatten(), "-k")
elif config.robot_type == RobotType.circle:
circle = plt.Circle((x, y), config.robot_radius, color="b")
plt.gcf().gca().add_artist(circle)
out_x, out_y = (np.array([x, y]) +
np.array([np.cos(yaw), np.sin(yaw)]) * config.robot_radius)
plt.plot([x, out_x], [y, out_y], "-k")
def main(gx=10.0, gy=10.0, robot_type=RobotType.circle):
print(__file__ + " start!!")
# initial state [x(m), y(m), yaw(rad), v(m/s), omega(rad/s)]
x = np.array([0.0, 0.0, math.pi / 8.0, 0.0, 0.0])
# goal position [x(m), y(m)]
goal = np.array([gx, gy])
# input [forward speed, yaw_rate]
config.robot_type = robot_type
trajectory = np.array(x)
ob = config.ob
while True:
u, predicted_trajectory = dwa_control(x, config, goal, ob)
x = motion(x, u, config.dt) # simulate robot
trajectory = np.vstack((trajectory, x)) # store state history
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(predicted_trajectory[:, 0], predicted_trajectory[:, 1], "-g")
plt.plot(x[0], x[1], "xr")
plt.plot(goal[0], goal[1], "xb")
plt.plot(ob[:, 0], ob[:, 1], "ok")
plot_robot(x[0], x[1], x[2], config)
plot_arrow(x[0], x[1], x[2])
plt.axis("equal")
plt.grid(True)
plt.pause(0.0001)
# check reaching goal
dist_to_goal = math.hypot(x[0] - goal[0], x[1] - goal[1])
if dist_to_goal <= config.robot_radius:
print("Goal!!")
break
print("Done")
if show_animation:
plt.plot(trajectory[:, 0], trajectory[:, 1], "-r")
plt.pause(0.0001)
plt.show()
if __name__ == '__main__':
main(robot_type=RobotType.rectangle)
# main(robot_type=RobotType.circle)
``` | /content/code_sandbox/PathPlanning/DynamicWindowApproach/dynamic_window_approach.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,749 |
```python
"""
Batch Informed Trees based path planning:
Uses a heuristic to efficiently search increasingly dense
RGGs while reusing previous information. Provides faster
convergence that RRT*, Informed RRT* and other sampling based
methods.
Uses lazy connecting by combining sampling based methods and A*
like incremental graph search algorithms.
author: Karan Chawla(@karanchawla)
Atsushi Sakai(@Atsushi_twi)
Reference: path_to_url
"""
import math
import random
import matplotlib.pyplot as plt
import numpy as np
show_animation = True
class RTree:
# Class to represent the explicit tree created
# while sampling through the state space
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] = []
@staticmethod
def get_root_id():
# return the id of the root of the tree
return 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
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)
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
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
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))
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
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
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))
class BITStar:
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)
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, 0], a1[0, 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
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
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()
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
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]))
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()
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
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)
def compute_distance_cost(self, vid, xid):
# L2 norm distance
start = np.array(self.tree.node_id_to_real_world_coord(vid))
stop = np.array(self.tree.node_id_to_real_world_coord(xid))
return np.linalg.norm(stop - start, 2)
# Sample free space confined in the radius of ball R
def informed_sample(self, m, cMax, cMin, xCenter, C):
samples = dict()
print("g_Score goal id: ", self.g_scores[self.goalId])
for i in range(m + 1):
if cMax < float('inf'):
r = [cMax / 2.0,
math.sqrt(cMax ** 2 - cMin ** 2) / 2.0,
math.sqrt(cMax ** 2 - cMin ** 2) / 2.0]
L = np.diag(r)
xBall = self.sample_unit_ball()
rnd = np.dot(np.dot(C, L), xBall) + xCenter
rnd = [rnd[(0, 0)], rnd[(1, 0)]]
random_id = self.tree.real_world_to_node_id(rnd)
samples[random_id] = rnd
else:
rnd = self.sample_free_space()
random_id = self.tree.real_world_to_node_id(rnd)
samples[random_id] = rnd
return samples
# Sample point in a unit ball
@staticmethod
def sample_unit_ball():
a = random.random()
b = random.random()
if b < a:
a, b = b, a
sample = (b * math.cos(2 * math.pi * a / b),
b * math.sin(2 * math.pi * a / b))
return np.array([[sample[0]], [sample[1]], [0]])
def sample_free_space(self):
rnd = [random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand)]
return rnd
def best_vertex_queue_value(self):
if len(self.vertex_queue) == 0:
return float('inf')
values = [self.g_scores[v]
+ self.compute_heuristic_cost(v, self.goalId) for v in
self.vertex_queue]
values.sort()
return values[0]
def best_edge_queue_value(self):
if len(self.edge_queue) == 0:
return float('inf')
# return the best value in the queue by score g_tau[v] + c(v,x) + h(x)
values = [self.g_scores[e[0]] + self.compute_distance_cost(e[0], e[1])
+ self.compute_heuristic_cost(e[1], self.goalId) for e in
self.edge_queue]
values.sort(reverse=True)
return values[0]
def best_in_vertex_queue(self):
# return the best value in the vertex queue
v_plus_values = [(v, self.g_scores[v] +
self.compute_heuristic_cost(v, self.goalId))
for v in self.vertex_queue]
v_plus_values = sorted(v_plus_values, key=lambda x: x[1])
# print(v_plus_values)
return v_plus_values[0][0]
def best_in_edge_queue(self):
e_and_values = [
(e[0], e[1], self.g_scores[e[0]] + self.compute_distance_cost(
e[0], e[1]) + self.compute_heuristic_cost(e[1], self.goalId))
for e in self.edge_queue]
e_and_values = sorted(e_and_values, key=lambda x: x[2])
return e_and_values[0][0], e_and_values[0][1]
def expand_vertex(self, vid):
self.vertex_queue.remove(vid)
# get the coordinates for given vid
currCoord = np.array(self.tree.node_id_to_real_world_coord(vid))
# get the nearest value in vertex for every one in samples where difference is
# less than the radius
neighbors = []
for sid, s_coord in self.samples.items():
s_coord = np.array(s_coord)
if np.linalg.norm(s_coord - currCoord, 2) <= self.r and sid != vid:
neighbors.append((sid, s_coord))
# add an edge to the edge queue is the path might improve the solution
for neighbor in neighbors:
sid = neighbor[0]
h_cost = self.compute_heuristic_cost(sid, self.goalId)
estimated_f_score = self.compute_distance_cost(
self.startId, vid) + h_cost + self.compute_distance_cost(vid,
sid)
if estimated_f_score < self.g_scores[self.goalId]:
self.edge_queue.append((vid, sid))
# add the vertex to the edge queue
self.add_vertex_to_edge_queue(vid, currCoord)
def add_vertex_to_edge_queue(self, vid, currCoord):
if vid not in self.old_vertices:
neighbors = []
for v, edges in self.tree.vertices.items():
if v != vid and (v, vid) not in self.edge_queue and \
(vid, v) not in self.edge_queue:
v_coord = self.tree.node_id_to_real_world_coord(v)
if np.linalg.norm(currCoord - v_coord, 2) <= self.r:
neighbors.append((vid, v_coord))
for neighbor in neighbors:
sid = neighbor[0]
estimated_f_score = self.compute_distance_cost(
self.startId, vid) + self.compute_distance_cost(
vid, sid) + self.compute_heuristic_cost(sid, self.goalId)
if estimated_f_score < self.g_scores[self.goalId] and (
self.g_scores[vid] +
self.compute_distance_cost(vid, sid)) < \
self.g_scores[sid]:
self.edge_queue.append((vid, sid))
def update_graph(self):
closedSet = []
openSet = []
currId = self.startId
openSet.append(currId)
while len(openSet) != 0:
# get the element with lowest f_score
currId = min(openSet, key=lambda x: self.f_scores[x])
# remove element from open set
openSet.remove(currId)
# Check if we're at the goal
if currId == self.goalId:
break
if currId not in closedSet:
closedSet.append(currId)
# find a non visited successor to the current node
successors = self.tree.vertices[currId]
for successor in successors:
if successor in closedSet:
continue
else:
# calculate tentative g score
g_score = self.g_scores[currId] + \
self.compute_distance_cost(currId, successor)
if successor not in openSet:
# add the successor to open set
openSet.append(successor)
elif g_score >= self.g_scores[successor]:
continue
# update g and f scores
self.g_scores[successor] = g_score
self.f_scores[
successor] = g_score + self.compute_heuristic_cost(
successor, self.goalId)
# store the parent and child
self.nodes[successor] = currId
def draw_graph(self, xCenter=None, cBest=None, cMin=None, eTheta=None,
samples=None, start=None, end=None):
plt.clf()
# 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])
for rnd in samples:
if rnd is not None:
plt.plot(rnd[0], rnd[1], "^k")
if cBest != float('inf'):
self.plot_ellipse(xCenter, cBest, cMin, eTheta)
if start is not None and end is not None:
plt.plot([start[0], start[1]], [end[0], end[1]], "-g")
for (ox, oy, size) in self.obstacleList:
plt.plot(ox, oy, "ok", ms=30 * size)
plt.plot(self.start[0], self.start[1], "xr")
plt.plot(self.goal[0], self.goal[1], "xr")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
plt.pause(0.01)
@staticmethod
def plot_ellipse(xCenter, cBest, cMin, eTheta): # pragma: no cover
a = math.sqrt(cBest ** 2 - cMin ** 2) / 2.0
b = cBest / 2.0
angle = math.pi / 2.0 - eTheta
cx = xCenter[0]
cy = xCenter[1]
t = np.arange(0, 2 * math.pi + 0.1, 0.1)
x = [a * math.cos(it) for it in t]
y = [b * math.sin(it) for it in t]
R = np.array([[math.cos(angle), math.sin(angle)],
[-math.sin(angle), math.cos(angle)]])
fx = R @ np.array([x, y])
px = np.array(fx[0, :] + cx).flatten()
py = np.array(fx[1, :] + cy).flatten()
plt.plot(cx, cy, "xc")
plt.plot(px, py, "--c")
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()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/BatchInformedRRTStar/batch_informed_rrtstar.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 5,551 |
```python
"""
A* grid planning
author: Atsushi Sakai(@Atsushi_twi)
Nikos Kanargias (nkana@tee.gr)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class AStarPlanner:
def __init__(self, ox, oy, resolution, rr):
"""
Initialize grid map for a star planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.resolution = resolution
self.rr = rr
self.min_x, self.min_y = 0, 0
self.max_x, self.max_y = 0, 0
self.obstacle_map = None
self.x_width, self.y_width = 0, 0
self.motion = self.get_motion_model()
self.calc_obstacle_map(ox, oy)
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
A star path search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(start_node)] = start_node
while True:
if len(open_set) == 0:
print("Open set is empty..")
break
c_id = min(
open_set,
key=lambda o: open_set[o].cost + self.calc_heuristic(goal_node,
open_set[
o]))
current = open_set[c_id]
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current.x, self.min_x),
self.calc_grid_position(current.y, self.min_y), "xc")
# 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 len(closed_set.keys()) % 10 == 0:
plt.pause(0.001)
if current.x == goal_node.x and current.y == goal_node.y:
print("Find goal")
goal_node.parent_index = current.parent_index
goal_node.cost = current.cost
break
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2], c_id)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if n_id in closed_set:
continue
if n_id not in open_set:
open_set[n_id] = node # discovered a new node
else:
if open_set[n_id].cost > node.cost:
# This path is the best until now. record it
open_set[n_id] = node
rx, ry = self.calc_final_path(goal_node, closed_set)
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
self.calc_grid_position(goal_node.y, self.min_y)]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(self.calc_grid_position(n.x, self.min_x))
ry.append(self.calc_grid_position(n.y, self.min_y))
parent_index = n.parent_index
return rx, ry
@staticmethod
def calc_heuristic(n1, n2):
w = 1.0 # weight of heuristic
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
return d
def calc_grid_position(self, index, min_position):
"""
calc grid position
:param index:
:param min_position:
:return:
"""
pos = index * self.resolution + min_position
return pos
def calc_xy_index(self, position, min_pos):
return round((position - min_pos) / self.resolution)
def calc_grid_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.min_x)
py = self.calc_grid_position(node.y, self.min_y)
if px < self.min_x:
return False
elif py < self.min_y:
return False
elif px >= self.max_x:
return False
elif py >= self.max_y:
return False
# collision check
if self.obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
# obstacle map generation
self.obstacle_map = [[False for _ in range(self.y_width)]
for _ in range(self.x_width)]
for ix in range(self.x_width):
x = self.calc_grid_position(ix, self.min_x)
for iy in range(self.y_width):
y = self.calc_grid_position(iy, self.min_y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obstacle_map[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
rx, ry = a_star.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/AStar/a_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,121 |
```python
"""
a star variants
author: Sarim Mehdi(muhammadsarim.mehdi@studio.unibo.it)
Source: path_to_url~amitp/GameProgramming/Variations.html
"""
import numpy as np
import matplotlib.pyplot as plt
show_animation = True
use_beam_search = False
use_iterative_deepening = False
use_dynamic_weighting = False
use_theta_star = False
use_jump_point = False
beam_capacity = 30
max_theta = 5
only_corners = False
max_corner = 5
w, epsilon, upper_bound_depth = 1, 4, 500
def draw_horizontal_line(start_x, start_y, length, o_x, o_y, o_dict):
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)] = True
def draw_vertical_line(start_x, start_y, length, o_x, o_y, o_dict):
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)] = True
def in_line_of_sight(obs_grid, x1, y1, x2, y2):
t = 0
while t <= 0.5:
xt = (1 - t) * x1 + t * x2
yt = (1 - t) * y1 + t * y2
if obs_grid[(int(xt), int(yt))]:
return False, None
xt = (1 - t) * x2 + t * x1
yt = (1 - t) * y2 + t * y1
if obs_grid[(int(xt), int(yt))]:
return False, None
t += 0.001
dist = np.linalg.norm(np.array([x1, y1] - np.array([x2, y2])))
return True, dist
def key_points(o_dict):
offsets1 = [(1, 0), (0, 1), (-1, 0), (1, 0)]
offsets2 = [(1, 1), (-1, 1), (-1, -1), (1, -1)]
offsets3 = [(0, 1), (-1, 0), (0, -1), (0, -1)]
c_list = []
for grid_point, obs_status in o_dict.items():
if obs_status:
continue
empty_space = True
x, y = grid_point
for i in [-1, 0, 1]:
for j in [-1, 0, 1]:
if (x + i, y + j) not in o_dict.keys():
continue
if o_dict[(x + i, y + j)]:
empty_space = False
break
if empty_space:
continue
for offset1, offset2, offset3 in zip(offsets1, offsets2, offsets3):
i1, j1 = offset1
i2, j2 = offset2
i3, j3 = offset3
if ((x + i1, y + j1) not in o_dict.keys()) or \
((x + i2, y + j2) not in o_dict.keys()) or \
((x + i3, y + j3) not in o_dict.keys()):
continue
obs_count = 0
if o_dict[(x + i1, y + j1)]:
obs_count += 1
if o_dict[(x + i2, y + j2)]:
obs_count += 1
if o_dict[(x + i3, y + j3)]:
obs_count += 1
if obs_count == 3 or obs_count == 1:
c_list.append((x, y))
if show_animation:
plt.plot(x, y, ".y")
break
if only_corners:
return c_list
e_list = []
for corner in c_list:
x1, y1 = corner
for other_corner in c_list:
x2, y2 = other_corner
if x1 == x2 and y1 == y2:
continue
reachable, _ = in_line_of_sight(o_dict, x1, y1, x2, y2)
if not reachable:
continue
x_m, y_m = int((x1 + x2) / 2), int((y1 + y2) / 2)
e_list.append((x_m, y_m))
if show_animation:
plt.plot(x_m, y_m, ".y")
return c_list + e_list
class SearchAlgo:
def __init__(self, obs_grid, goal_x, goal_y, start_x, start_y,
limit_x, limit_y, corner_list=None):
self.start_pt = [start_x, start_y]
self.goal_pt = [goal_x, goal_y]
self.obs_grid = obs_grid
g_cost, h_cost = 0, self.get_hval(start_x, start_y, goal_x, goal_y)
f_cost = g_cost + h_cost
self.all_nodes, self.open_set = {}, []
if use_jump_point:
for corner in corner_list:
i, j = corner
h_c = self.get_hval(i, j, goal_x, goal_y)
self.all_nodes[(i, j)] = {'pos': [i, j], 'pred': None,
'gcost': np.inf, 'hcost': h_c,
'fcost': np.inf,
'open': True, 'in_open_list': False}
self.all_nodes[tuple(self.goal_pt)] = \
{'pos': self.goal_pt, 'pred': None,
'gcost': np.inf, 'hcost': 0, 'fcost': np.inf,
'open': True, 'in_open_list': True}
else:
for i in range(limit_x):
for j in range(limit_y):
h_c = self.get_hval(i, j, goal_x, goal_y)
self.all_nodes[(i, j)] = {'pos': [i, j], 'pred': None,
'gcost': np.inf, 'hcost': h_c,
'fcost': np.inf,
'open': True,
'in_open_list': False}
self.all_nodes[tuple(self.start_pt)] = \
{'pos': self.start_pt, 'pred': None,
'gcost': g_cost, 'hcost': h_cost, 'fcost': f_cost,
'open': True, 'in_open_list': True}
self.open_set.append(self.all_nodes[tuple(self.start_pt)])
@staticmethod
def get_hval(x1, y1, x2, y2):
x, y = x1, y1
val = 0
while x != x2 or y != y2:
if x != x2 and y != y2:
val += 14
else:
val += 10
x, y = x + np.sign(x2 - x), y + np.sign(y2 - y)
return val
def get_farthest_point(self, x, y, i, j):
i_temp, j_temp = i, j
counter = 1
got_goal = False
while not self.obs_grid[(x + i_temp, y + j_temp)] and \
counter < max_theta:
i_temp += i
j_temp += j
counter += 1
if [x + i_temp, y + j_temp] == self.goal_pt:
got_goal = True
break
if (x + i_temp, y + j_temp) not in self.obs_grid.keys():
break
return i_temp - 2*i, j_temp - 2*j, counter, got_goal
def jump_point(self):
"""Jump point: Instead of exploring all empty spaces of the
map, just explore the corners."""
goal_found = False
while len(self.open_set) > 0:
self.open_set = sorted(self.open_set, key=lambda x: x['fcost'])
lowest_f = self.open_set[0]['fcost']
lowest_h = self.open_set[0]['hcost']
lowest_g = self.open_set[0]['gcost']
p = 0
for p_n in self.open_set[1:]:
if p_n['fcost'] == lowest_f and \
p_n['gcost'] < lowest_g:
lowest_g = p_n['gcost']
p += 1
elif p_n['fcost'] == lowest_f and \
p_n['gcost'] == lowest_g and \
p_n['hcost'] < lowest_h:
lowest_h = p_n['hcost']
p += 1
else:
break
current_node = self.all_nodes[tuple(self.open_set[p]['pos'])]
x1, y1 = current_node['pos']
for cand_pt, cand_node in self.all_nodes.items():
x2, y2 = cand_pt
if x1 == x2 and y1 == y2:
continue
if np.linalg.norm(np.array([x1, y1] -
np.array([x2, y2]))) > max_corner:
continue
reachable, offset = in_line_of_sight(self.obs_grid, x1,
y1, x2, y2)
if not reachable:
continue
if list(cand_pt) == self.goal_pt:
current_node['open'] = False
self.all_nodes[tuple(cand_pt)]['pred'] = \
current_node['pos']
goal_found = True
break
g_cost = offset + current_node['gcost']
h_cost = self.all_nodes[cand_pt]['hcost']
f_cost = g_cost + h_cost
cand_pt = tuple(cand_pt)
if f_cost < self.all_nodes[cand_pt]['fcost']:
self.all_nodes[cand_pt]['pred'] = current_node['pos']
self.all_nodes[cand_pt]['gcost'] = g_cost
self.all_nodes[cand_pt]['fcost'] = f_cost
if not self.all_nodes[cand_pt]['in_open_list']:
self.open_set.append(self.all_nodes[cand_pt])
self.all_nodes[cand_pt]['in_open_list'] = True
if show_animation:
plt.plot(cand_pt[0], cand_pt[1], "r*")
if goal_found:
break
if show_animation:
plt.pause(0.001)
if goal_found:
current_node = self.all_nodes[tuple(self.goal_pt)]
while goal_found:
if current_node['pred'] is None:
break
x = [current_node['pos'][0], current_node['pred'][0]]
y = [current_node['pos'][1], current_node['pred'][1]]
current_node = self.all_nodes[tuple(current_node['pred'])]
if show_animation:
plt.plot(x, y, "b")
plt.pause(0.001)
if goal_found:
break
current_node['open'] = False
current_node['in_open_list'] = False
if show_animation:
plt.plot(current_node['pos'][0], current_node['pos'][1], "g*")
del self.open_set[p]
current_node['fcost'], current_node['hcost'] = np.inf, np.inf
if show_animation:
plt.title('Jump Point')
plt.show()
def a_star(self):
"""Beam search: Maintain an open list of just 30 nodes.
If more than 30 nodes, then get rid of nodes with high
f values.
Iterative deepening: At every iteration, get a cut-off
value for the f cost. This cut-off is minimum of the f
value of all nodes whose f value is higher than the
current cut-off value. Nodes with f value higher than
the current cut off value are not put in the open set.
Dynamic weighting: Multiply heuristic with the following:
(1 + epsilon - (epsilon*d)/N) where d is the current
iteration of loop and N is upper bound on number of
iterations.
Theta star: Same as A star but you don't need to move
one neighbor at a time. In fact, you can look for the
next node as far out as you can as long as there is a
clear line of sight from your current node to that node."""
if show_animation:
if use_beam_search:
plt.title('A* with beam search')
elif use_iterative_deepening:
plt.title('A* with iterative deepening')
elif use_dynamic_weighting:
plt.title('A* with dynamic weighting')
elif use_theta_star:
plt.title('Theta*')
else:
plt.title('A*')
goal_found = False
curr_f_thresh = np.inf
depth = 0
no_valid_f = False
w = None
while len(self.open_set) > 0:
self.open_set = sorted(self.open_set, key=lambda x: x['fcost'])
lowest_f = self.open_set[0]['fcost']
lowest_h = self.open_set[0]['hcost']
lowest_g = self.open_set[0]['gcost']
p = 0
for p_n in self.open_set[1:]:
if p_n['fcost'] == lowest_f and \
p_n['gcost'] < lowest_g:
lowest_g = p_n['gcost']
p += 1
elif p_n['fcost'] == lowest_f and \
p_n['gcost'] == lowest_g and \
p_n['hcost'] < lowest_h:
lowest_h = p_n['hcost']
p += 1
else:
break
current_node = self.all_nodes[tuple(self.open_set[p]['pos'])]
while len(self.open_set) > beam_capacity and use_beam_search:
del self.open_set[-1]
f_cost_list = []
if use_dynamic_weighting:
w = (1 + epsilon - epsilon*depth/upper_bound_depth)
for i in range(-1, 2):
for j in range(-1, 2):
x, y = current_node['pos']
if (i == 0 and j == 0) or \
((x + i, y + j) not in self.obs_grid.keys()):
continue
if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
offset = 10
else:
offset = 14
if use_theta_star:
new_i, new_j, counter, goal_found = \
self.get_farthest_point(x, y, i, j)
offset = offset * counter
cand_pt = [current_node['pos'][0] + new_i,
current_node['pos'][1] + new_j]
else:
cand_pt = [current_node['pos'][0] + i,
current_node['pos'][1] + j]
if use_theta_star and goal_found:
current_node['open'] = False
cand_pt = self.goal_pt
self.all_nodes[tuple(cand_pt)]['pred'] = \
current_node['pos']
break
if cand_pt == self.goal_pt:
current_node['open'] = False
self.all_nodes[tuple(cand_pt)]['pred'] = \
current_node['pos']
goal_found = True
break
cand_pt = tuple(cand_pt)
no_valid_f = self.update_node_cost(cand_pt, curr_f_thresh,
current_node,
f_cost_list, no_valid_f,
offset, w)
if goal_found:
break
if show_animation:
plt.pause(0.001)
if goal_found:
current_node = self.all_nodes[tuple(self.goal_pt)]
while goal_found:
if current_node['pred'] is None:
break
if use_theta_star or use_jump_point:
x, y = [current_node['pos'][0], current_node['pred'][0]], \
[current_node['pos'][1], current_node['pred'][1]]
if show_animation:
plt.plot(x, y, "b")
else:
if show_animation:
plt.plot(current_node['pred'][0],
current_node['pred'][1], "b*")
current_node = self.all_nodes[tuple(current_node['pred'])]
if goal_found:
break
if use_iterative_deepening and f_cost_list:
curr_f_thresh = min(f_cost_list)
if use_iterative_deepening and not f_cost_list:
curr_f_thresh = np.inf
if use_iterative_deepening and not f_cost_list and no_valid_f:
current_node['fcost'], current_node['hcost'] = np.inf, np.inf
continue
current_node['open'] = False
current_node['in_open_list'] = False
if show_animation:
plt.plot(current_node['pos'][0], current_node['pos'][1], "g*")
del self.open_set[p]
current_node['fcost'], current_node['hcost'] = np.inf, np.inf
depth += 1
if show_animation:
plt.show()
def update_node_cost(self, cand_pt, curr_f_thresh, current_node,
f_cost_list, no_valid_f, offset, w):
if not self.obs_grid[tuple(cand_pt)] and \
self.all_nodes[cand_pt]['open']:
g_cost = offset + current_node['gcost']
h_cost = self.all_nodes[cand_pt]['hcost']
if use_dynamic_weighting:
h_cost = h_cost * w
f_cost = g_cost + h_cost
if f_cost < self.all_nodes[cand_pt]['fcost'] and \
f_cost <= curr_f_thresh:
f_cost_list.append(f_cost)
self.all_nodes[cand_pt]['pred'] = \
current_node['pos']
self.all_nodes[cand_pt]['gcost'] = g_cost
self.all_nodes[cand_pt]['fcost'] = f_cost
if not self.all_nodes[cand_pt]['in_open_list']:
self.open_set.append(self.all_nodes[cand_pt])
self.all_nodes[cand_pt]['in_open_list'] = True
if show_animation:
plt.plot(cand_pt[0], cand_pt[1], "r*")
if curr_f_thresh < f_cost < \
self.all_nodes[cand_pt]['fcost']:
no_valid_f = True
return no_valid_f
def main():
# set obstacle positions
obs_dict = {}
for i in range(51):
for j in range(51):
obs_dict[(i, j)] = False
o_x, o_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)
draw_vertical_line(48, 0, 50, o_x, o_y, obs_dict)
draw_horizontal_line(0, 0, 50, o_x, o_y, obs_dict)
draw_horizontal_line(0, 48, 50, o_x, o_y, obs_dict)
# 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)
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)
if show_animation:
plt.plot(o_x, o_y, ".k")
plt.plot(s_x, s_y, "og")
plt.plot(g_x, g_y, "xb")
plt.grid(True)
if use_jump_point:
keypoint_list = key_points(obs_dict)
search_obj = SearchAlgo(obs_dict, g_x, g_y, s_x, s_y, 101, 101,
keypoint_list)
search_obj.jump_point()
else:
search_obj = SearchAlgo(obs_dict, g_x, g_y, s_x, s_y, 101, 101)
search_obj.a_star()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/AStar/a_star_variants.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 4,817 |
```python
"""
A* algorithm
Author: Weicent
randomly generate obstacles, start and goal point
searching path from start and end simultaneously
"""
import numpy as np
import matplotlib.pyplot as plt
import math
show_animation = True
class Node:
"""node with properties of g, h, coordinate and parent node"""
def __init__(self, G=0, H=0, coordinate=None, parent=None):
self.G = G
self.H = H
self.F = G + H
self.parent = parent
self.coordinate = coordinate
def reset_f(self):
self.F = self.G + self.H
def hcost(node_coordinate, goal):
dx = abs(node_coordinate[0] - goal[0])
dy = abs(node_coordinate[1] - goal[1])
hcost = dx + dy
return hcost
def gcost(fixed_node, update_node_coordinate):
dx = abs(fixed_node.coordinate[0] - update_node_coordinate[0])
dy = abs(fixed_node.coordinate[1] - update_node_coordinate[1])
gc = math.hypot(dx, dy) # gc = move from fixed_node to update_node
gcost = fixed_node.G + gc # gcost = move from start point to update_node
return gcost
def boundary_and_obstacles(start, goal, top_vertex, bottom_vertex, obs_number):
"""
:param start: start coordinate
:param goal: goal coordinate
:param top_vertex: top right vertex coordinate of boundary
:param bottom_vertex: bottom left vertex coordinate of boundary
:param obs_number: number of obstacles generated in the map
:return: boundary_obstacle array, obstacle list
"""
# below can be merged into a rectangle boundary
ay = list(range(bottom_vertex[1], top_vertex[1]))
ax = [bottom_vertex[0]] * len(ay)
cy = ay
cx = [top_vertex[0]] * len(cy)
bx = list(range(bottom_vertex[0] + 1, top_vertex[0]))
by = [bottom_vertex[1]] * len(bx)
dx = [bottom_vertex[0]] + bx + [top_vertex[0]]
dy = [top_vertex[1]] * len(dx)
# generate random obstacles
ob_x = np.random.randint(bottom_vertex[0] + 1,
top_vertex[0], obs_number).tolist()
ob_y = np.random.randint(bottom_vertex[1] + 1,
top_vertex[1], obs_number).tolist()
# x y coordinate in certain order for boundary
x = ax + bx + cx + dx
y = ay + by + cy + dy
obstacle = np.vstack((ob_x, ob_y)).T.tolist()
# remove start and goal coordinate in obstacle list
obstacle = [coor for coor in obstacle if coor != start and coor != goal]
obs_array = np.array(obstacle)
bound = np.vstack((x, y)).T
bound_obs = np.vstack((bound, obs_array))
return bound_obs, obstacle
def find_neighbor(node, ob, closed):
# generate neighbors in certain condition
ob_list = ob.tolist()
neighbor: list = []
for x in range(node.coordinate[0] - 1, node.coordinate[0] + 2):
for y in range(node.coordinate[1] - 1, node.coordinate[1] + 2):
if [x, y] not in ob_list:
# find all possible neighbor nodes
neighbor.append([x, y])
# remove node violate the motion rule
# 1. remove node.coordinate itself
neighbor.remove(node.coordinate)
# 2. remove neighbor nodes who cross through two diagonal
# positioned obstacles since there is no enough space for
# robot to go through two diagonal positioned obstacles
# top bottom left right neighbors of node
top_nei = [node.coordinate[0], node.coordinate[1] + 1]
bottom_nei = [node.coordinate[0], node.coordinate[1] - 1]
left_nei = [node.coordinate[0] - 1, node.coordinate[1]]
right_nei = [node.coordinate[0] + 1, node.coordinate[1]]
# neighbors in four vertex
lt_nei = [node.coordinate[0] - 1, node.coordinate[1] + 1]
rt_nei = [node.coordinate[0] + 1, node.coordinate[1] + 1]
lb_nei = [node.coordinate[0] - 1, node.coordinate[1] - 1]
rb_nei = [node.coordinate[0] + 1, node.coordinate[1] - 1]
# remove the unnecessary neighbors
if top_nei and left_nei in ob_list and lt_nei in neighbor:
neighbor.remove(lt_nei)
if top_nei and right_nei in ob_list and rt_nei in neighbor:
neighbor.remove(rt_nei)
if bottom_nei and left_nei in ob_list and lb_nei in neighbor:
neighbor.remove(lb_nei)
if bottom_nei and right_nei in ob_list and rb_nei in neighbor:
neighbor.remove(rb_nei)
neighbor = [x for x in neighbor if x not in closed]
return neighbor
def find_node_index(coordinate, node_list):
# find node index in the node list via its coordinate
ind = 0
for node in node_list:
if node.coordinate == coordinate:
target_node = node
ind = node_list.index(target_node)
break
return ind
def find_path(open_list, closed_list, goal, obstacle):
# searching for the path, update open and closed list
# obstacle = obstacle and boundary
flag = len(open_list)
for i in range(flag):
node = open_list[0]
open_coordinate_list = [node.coordinate for node in open_list]
closed_coordinate_list = [node.coordinate for node in closed_list]
temp = find_neighbor(node, obstacle, closed_coordinate_list)
for element in temp:
if element in closed_list:
continue
elif element in open_coordinate_list:
# if node in open list, update g value
ind = open_coordinate_list.index(element)
new_g = gcost(node, element)
if new_g <= open_list[ind].G:
open_list[ind].G = new_g
open_list[ind].reset_f()
open_list[ind].parent = node
else: # new coordinate, create corresponding node
ele_node = Node(coordinate=element, parent=node,
G=gcost(node, element), H=hcost(element, goal))
open_list.append(ele_node)
open_list.remove(node)
closed_list.append(node)
open_list.sort(key=lambda x: x.F)
return open_list, closed_list
def node_to_coordinate(node_list):
# convert node list into coordinate list and array
coordinate_list = [node.coordinate for node in node_list]
return coordinate_list
def check_node_coincide(close_ls1, closed_ls2):
"""
:param close_ls1: node closed list for searching from start
:param closed_ls2: node closed list for searching from end
:return: intersect node list for above two
"""
# check if node in close_ls1 intersect with node in closed_ls2
cl1 = node_to_coordinate(close_ls1)
cl2 = node_to_coordinate(closed_ls2)
intersect_ls = [node for node in cl1 if node in cl2]
return intersect_ls
def find_surrounding(coordinate, obstacle):
# find obstacles around node, help to draw the borderline
boundary: list = []
for x in range(coordinate[0] - 1, coordinate[0] + 2):
for y in range(coordinate[1] - 1, coordinate[1] + 2):
if [x, y] in obstacle:
boundary.append([x, y])
return boundary
def get_border_line(node_closed_ls, obstacle):
# if no path, find border line which confine goal or robot
border: list = []
coordinate_closed_ls = node_to_coordinate(node_closed_ls)
for coordinate in coordinate_closed_ls:
temp = find_surrounding(coordinate, obstacle)
border = border + temp
border_ary = np.array(border)
return border_ary
def get_path(org_list, goal_list, coordinate):
# get path from start to end
path_org: list = []
path_goal: list = []
ind = find_node_index(coordinate, org_list)
node = org_list[ind]
while node != org_list[0]:
path_org.append(node.coordinate)
node = node.parent
path_org.append(org_list[0].coordinate)
ind = find_node_index(coordinate, goal_list)
node = goal_list[ind]
while node != goal_list[0]:
path_goal.append(node.coordinate)
node = node.parent
path_goal.append(goal_list[0].coordinate)
path_org.reverse()
path = path_org + path_goal
path = np.array(path)
return path
def random_coordinate(bottom_vertex, top_vertex):
# generate random coordinates inside maze
coordinate = [np.random.randint(bottom_vertex[0] + 1, top_vertex[0]),
np.random.randint(bottom_vertex[1] + 1, top_vertex[1])]
return coordinate
def draw(close_origin, close_goal, start, end, bound):
# plot the map
if not close_goal.tolist(): # ensure the close_goal not empty
# in case of the obstacle number is really large (>4500), the
# origin is very likely blocked at the first search, and then
# the program is over and the searching from goal to origin
# will not start, which remain the closed_list for goal == []
# in order to plot the map, add the end coordinate to array
close_goal = np.array([end])
plt.cla()
plt.gcf().set_size_inches(11, 9, forward=True)
plt.axis('equal')
plt.plot(close_origin[:, 0], close_origin[:, 1], 'oy')
plt.plot(close_goal[:, 0], close_goal[:, 1], 'og')
plt.plot(bound[:, 0], bound[:, 1], 'sk')
plt.plot(end[0], end[1], '*b', label='Goal')
plt.plot(start[0], start[1], '^b', label='Origin')
plt.legend()
plt.pause(0.0001)
def draw_control(org_closed, goal_closed, flag, start, end, bound, obstacle):
"""
control the plot process, evaluate if the searching finished
flag == 0 : draw the searching process and plot path
flag == 1 or 2 : start or end is blocked, draw the border line
"""
stop_loop = 0 # stop sign for the searching
org_closed_ls = node_to_coordinate(org_closed)
org_array = np.array(org_closed_ls)
goal_closed_ls = node_to_coordinate(goal_closed)
goal_array = np.array(goal_closed_ls)
path = None
if show_animation: # draw the searching process
draw(org_array, goal_array, start, end, bound)
if flag == 0:
node_intersect = check_node_coincide(org_closed, goal_closed)
if node_intersect: # a path is find
path = get_path(org_closed, goal_closed, node_intersect[0])
stop_loop = 1
print('Path found!')
if show_animation: # draw the path
plt.plot(path[:, 0], path[:, 1], '-r')
plt.title('Robot Arrived', size=20, loc='center')
plt.pause(0.01)
plt.show()
elif flag == 1: # start point blocked first
stop_loop = 1
print('There is no path to the goal! Start point is blocked!')
elif flag == 2: # end point blocked first
stop_loop = 1
print('There is no path to the goal! End point is blocked!')
if show_animation: # blocked case, draw the border line
info = 'There is no path to the goal!' \
' Robot&Goal are split by border' \
' shown in red \'x\'!'
if flag == 1:
border = get_border_line(org_closed, obstacle)
plt.plot(border[:, 0], border[:, 1], 'xr')
plt.title(info, size=14, loc='center')
plt.pause(0.01)
plt.show()
elif flag == 2:
border = get_border_line(goal_closed, obstacle)
plt.plot(border[:, 0], border[:, 1], 'xr')
plt.title(info, size=14, loc='center')
plt.pause(0.01)
plt.show()
return stop_loop, path
def searching_control(start, end, bound, obstacle):
"""manage the searching process, start searching from two side"""
# initial origin node and end node
origin = Node(coordinate=start, H=hcost(start, end))
goal = Node(coordinate=end, H=hcost(end, start))
# list for searching from origin to goal
origin_open: list = [origin]
origin_close: list = []
# list for searching from goal to origin
goal_open = [goal]
goal_close: list = []
# initial target
target_goal = end
# flag = 0 (not blocked) 1 (start point blocked) 2 (end point blocked)
flag = 0 # init flag
path = None
while True:
# searching from start to end
origin_open, origin_close = \
find_path(origin_open, origin_close, target_goal, bound)
if not origin_open: # no path condition
flag = 1 # origin node is blocked
draw_control(origin_close, goal_close, flag, start, end, bound,
obstacle)
break
# update target for searching from end to start
target_origin = min(origin_open, key=lambda x: x.F).coordinate
# searching from end to start
goal_open, goal_close = \
find_path(goal_open, goal_close, target_origin, bound)
if not goal_open: # no path condition
flag = 2 # goal is blocked
draw_control(origin_close, goal_close, flag, start, end, bound,
obstacle)
break
# update target for searching from start to end
target_goal = min(goal_open, key=lambda x: x.F).coordinate
# continue searching, draw the process
stop_sign, path = draw_control(origin_close, goal_close, flag, start,
end, bound, obstacle)
if stop_sign:
break
return path
def main(obstacle_number=1500):
print(__file__ + ' start!')
top_vertex = [60, 60] # top right vertex of boundary
bottom_vertex = [0, 0] # bottom left vertex of boundary
# generate start and goal point randomly
start = random_coordinate(bottom_vertex, top_vertex)
end = random_coordinate(bottom_vertex, top_vertex)
# generate boundary and obstacles
bound, obstacle = boundary_and_obstacles(start, end, top_vertex,
bottom_vertex,
obstacle_number)
path = searching_control(start, end, bound, obstacle)
if not show_animation:
print(path)
if __name__ == '__main__':
main(obstacle_number=1500)
``` | /content/code_sandbox/PathPlanning/AStar/a_star_searching_from_two_side.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,412 |
```python
"""
Path planning Sample Code with Randomized Rapidly-Exploring Random
Trees with sobol low discrepancy sampler(RRTSobol).
Sobol wiki path_to_url
The goal of low discrepancy samplers is to generate a sequence of points that
optimizes a criterion called dispersion. Intuitively, the idea is to place
samples to cover the exploration space in a way that makes the largest
uncovered area be as small as possible. This generalizes of the idea of grid
resolution. For a grid, the resolution may be selected by defining the step
size for each axis. As the step size is decreased, the resolution increases.
If a grid-based motion planning algorithm can increase the resolution
arbitrarily, it becomes resolution complete. Dispersion can be considered as a
powerful generalization of the notion of resolution.
Taken from
LaValle, Steven M. Planning algorithms. Cambridge university press, 2006.
authors:
First implementation AtsushiSakai(@Atsushi_twi)
Sobol sampler Rafael A.
Rojas (rafaelrojasmiliani@gmail.com)
"""
import math
import random
import sys
import matplotlib.pyplot as plt
import numpy as np
from sobol import sobol_quasirand
show_animation = True
class RRTSobol:
"""
Class for RRTSobol planning
"""
class Node:
"""
RRTSobol Node
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.path_x = []
self.path_y = []
self.parent = None
def __init__(self,
start,
goal,
obstacle_list,
rand_area,
expand_dis=3.0,
path_resolution=0.5,
goal_sample_rate=5,
max_iter=500,
robot_radius=0.0):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacle_list:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1])
self.end = self.Node(goal[0], goal[1])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.expand_dis = expand_dis
self.path_resolution = path_resolution
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.node_list = []
self.sobol_inter_ = 0
self.robot_radius = robot_radius
def planning(self, animation=True):
"""
rrt path planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
rnd_node = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)
nearest_node = self.node_list[nearest_ind]
new_node = self.steer(nearest_node, rnd_node, self.expand_dis)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
self.node_list.append(new_node)
if animation and i % 5 == 0:
self.draw_graph(rnd_node)
if self.calc_dist_to_goal(self.node_list[-1].x,
self.node_list[-1].y) <= self.expand_dis:
final_node = self.steer(self.node_list[-1], self.end,
self.expand_dis)
if self.check_collision(
final_node, self.obstacle_list, self.robot_radius):
return self.generate_final_course(len(self.node_list) - 1)
if animation and i % 5:
self.draw_graph(rnd_node)
return None # cannot find path
def steer(self, from_node, to_node, extend_length=float("inf")):
new_node = self.Node(from_node.x, from_node.y)
d, theta = self.calc_distance_and_angle(new_node, to_node)
new_node.path_x = [new_node.x]
new_node.path_y = [new_node.y]
if extend_length > d:
extend_length = d
n_expand = math.floor(extend_length / self.path_resolution)
for _ in range(n_expand):
new_node.x += self.path_resolution * math.cos(theta)
new_node.y += self.path_resolution * math.sin(theta)
new_node.path_x.append(new_node.x)
new_node.path_y.append(new_node.y)
d, _ = self.calc_distance_and_angle(new_node, to_node)
if d <= self.path_resolution:
new_node.path_x.append(to_node.x)
new_node.path_y.append(to_node.y)
new_node.x = to_node.x
new_node.y = to_node.y
new_node.parent = from_node
return new_node
def generate_final_course(self, goal_ind):
path = [[self.end.x, self.end.y]]
node = self.node_list[goal_ind]
while node.parent is not None:
path.append([node.x, node.y])
node = node.parent
path.append([node.x, node.y])
return path
def calc_dist_to_goal(self, x, y):
dx = x - self.end.x
dy = y - self.end.y
return math.hypot(dx, dy)
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rand_coordinates, n = sobol_quasirand(2, self.sobol_inter_)
rand_coordinates = self.min_rand + \
rand_coordinates*(self.max_rand - self.min_rand)
self.sobol_inter_ = n
rnd = self.Node(*rand_coordinates)
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y)
return rnd
def draw_graph(self, rnd=None):
plt.clf()
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect(
'key_release_event',
lambda event: [sys.exit(0) if event.key == 'escape' else None])
if rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
if self.robot_radius >= 0.0:
self.plot_circle(rnd.x, rnd.y, self.robot_radius, '-r')
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
self.plot_circle(ox, oy, size)
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis("equal")
plt.axis([-2, 15, -2, 15])
plt.grid(True)
plt.pause(0.01)
@staticmethod
def plot_circle(x, y, size, color="-b"): # pragma: no cover
deg = list(range(0, 360, 5))
deg.append(0)
xl = [x + size * math.cos(np.deg2rad(d)) for d in deg]
yl = [y + size * math.sin(np.deg2rad(d)) for d in deg]
plt.plot(xl, yl, color)
@staticmethod
def get_nearest_node_index(node_list, rnd_node):
dlist = [(node.x - rnd_node.x)**2 + (node.y - rnd_node.y)**2
for node in node_list]
minind = dlist.index(min(dlist))
return minind
@staticmethod
def check_collision(node, obstacle_list, robot_radius):
if node is None:
return False
for (ox, oy, size) in obstacle_list:
dx_list = [ox - x for x in node.path_x]
dy_list = [oy - y for y in node.path_y]
d_list = [dx * dx + dy * dy for (dx, dy) in zip(dx_list, dy_list)]
if min(d_list) <= (size+robot_radius)**2:
return False # collision
return True # safe
@staticmethod
def calc_distance_and_angle(from_node, to_node):
dx = to_node.x - from_node.x
dy = to_node.y - from_node.y
d = math.hypot(dx, dy)
theta = math.atan2(dy, dx)
return d, theta
def main(gx=6.0, gy=10.0):
print("start " + __file__)
# ====Search Path with RRTSobol====
obstacle_list = [(5, 5, 1), (3, 6, 2), (3, 8, 2), (3, 10, 2), (7, 5, 2),
(9, 5, 2), (8, 10, 1)] # [x, y, radius]
# Set Initial parameters
rrt = RRTSobol(
start=[0, 0],
goal=[gx, gy],
rand_area=[-2, 15],
obstacle_list=obstacle_list,
robot_radius=0.8)
path = rrt.planning(animation=show_animation)
if path is None:
print("Cannot find path")
else:
print("found path!!")
# Draw final path
if show_animation:
rrt.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.01) # Need for Mac
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRT/rrt_with_sobol_sampler.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,156 |
```python
"""
Path planning Sample Code with RRT with path smoothing
@author: AtsushiSakai(@Atsushi_twi)
"""
import math
import random
import matplotlib.pyplot as plt
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent))
from rrt import RRT
show_animation = True
def get_path_length(path):
le = 0
for i in range(len(path) - 1):
dx = path[i + 1][0] - path[i][0]
dy = path[i + 1][1] - path[i][1]
d = math.hypot(dx, dy)
le += d
return le
def get_target_point(path, targetL):
le = 0
ti = 0
lastPairLen = 0
for i in range(len(path) - 1):
dx = path[i + 1][0] - path[i][0]
dy = path[i + 1][1] - path[i][1]
d = math.hypot(dx, dy)
le += d
if le >= targetL:
ti = i - 1
lastPairLen = d
break
partRatio = (le - targetL) / lastPairLen
x = path[ti][0] + (path[ti + 1][0] - path[ti][0]) * partRatio
y = path[ti][1] + (path[ti + 1][1] - path[ti][1]) * partRatio
return [x, y, ti]
def line_collision_check(first, second, obstacleList):
# Line Equation
x1 = first[0]
y1 = first[1]
x2 = second[0]
y2 = second[1]
try:
a = y2 - y1
b = -(x2 - x1)
c = y2 * (x2 - x1) - x2 * (y2 - y1)
except ZeroDivisionError:
return False
for (ox, oy, size) in obstacleList:
d = abs(a * ox + b * oy + c) / (math.hypot(a, b))
if d <= size:
return False
return True # OK
def path_smoothing(path, max_iter, obstacle_list):
le = get_path_length(path)
for i in range(max_iter):
# Sample two points
pickPoints = [random.uniform(0, le), random.uniform(0, le)]
pickPoints.sort()
first = get_target_point(path, pickPoints[0])
second = get_target_point(path, pickPoints[1])
if first[2] <= 0 or second[2] <= 0:
continue
if (second[2] + 1) > len(path):
continue
if second[2] == first[2]:
continue
# collision check
if not line_collision_check(first, second, obstacle_list):
continue
# Create New path
newPath = []
newPath.extend(path[:first[2] + 1])
newPath.append([first[0], first[1]])
newPath.append([second[0], second[1]])
newPath.extend(path[second[2] + 1:])
path = newPath
le = get_path_length(path)
return path
def main():
# ====Search Path with RRT====
# Parameter
obstacleList = [
(5, 5, 1),
(3, 6, 2),
(3, 8, 2),
(3, 10, 2),
(7, 5, 2),
(9, 5, 2)
] # [x,y,size]
rrt = RRT(start=[0, 0], goal=[6, 10],
rand_area=[-2, 15], obstacle_list=obstacleList)
path = rrt.planning(animation=show_animation)
# Path smoothing
maxIter = 1000
smoothedPath = path_smoothing(path, maxIter, obstacleList)
# Draw final path
if show_animation:
rrt.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.plot([x for (x, y) in smoothedPath], [
y for (x, y) in smoothedPath], '-c')
plt.grid(True)
plt.pause(0.01) # Need for Mac
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRT/rrt_with_pathsmoothing.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,021 |
```python
"""
Path planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT)
author: AtsushiSakai(@Atsushi_twi)
"""
import math
import random
import matplotlib.pyplot as plt
import numpy as np
show_animation = True
class RRT:
"""
Class for RRT planning
"""
class Node:
"""
RRT Node
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.path_x = []
self.path_y = []
self.parent = None
class AreaBounds:
def __init__(self, area):
self.xmin = float(area[0])
self.xmax = float(area[1])
self.ymin = float(area[2])
self.ymax = float(area[3])
def __init__(self,
start,
goal,
obstacle_list,
rand_area,
expand_dis=3.0,
path_resolution=0.5,
goal_sample_rate=5,
max_iter=500,
play_area=None,
robot_radius=0.0,
):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
play_area:stay inside this area [xmin,xmax,ymin,ymax]
robot_radius: robot body modeled as circle with given radius
"""
self.start = self.Node(start[0], start[1])
self.end = self.Node(goal[0], goal[1])
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
if play_area is not None:
self.play_area = self.AreaBounds(play_area)
else:
self.play_area = None
self.expand_dis = expand_dis
self.path_resolution = path_resolution
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.obstacle_list = obstacle_list
self.node_list = []
self.robot_radius = robot_radius
def planning(self, animation=True):
"""
rrt path planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
rnd_node = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)
nearest_node = self.node_list[nearest_ind]
new_node = self.steer(nearest_node, rnd_node, self.expand_dis)
if self.check_if_outside_play_area(new_node, self.play_area) and \
self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
self.node_list.append(new_node)
if animation and i % 5 == 0:
self.draw_graph(rnd_node)
if self.calc_dist_to_goal(self.node_list[-1].x,
self.node_list[-1].y) <= self.expand_dis:
final_node = self.steer(self.node_list[-1], self.end,
self.expand_dis)
if self.check_collision(
final_node, self.obstacle_list, self.robot_radius):
return self.generate_final_course(len(self.node_list) - 1)
if animation and i % 5:
self.draw_graph(rnd_node)
return None # cannot find path
def steer(self, from_node, to_node, extend_length=float("inf")):
new_node = self.Node(from_node.x, from_node.y)
d, theta = self.calc_distance_and_angle(new_node, to_node)
new_node.path_x = [new_node.x]
new_node.path_y = [new_node.y]
if extend_length > d:
extend_length = d
n_expand = math.floor(extend_length / self.path_resolution)
for _ in range(n_expand):
new_node.x += self.path_resolution * math.cos(theta)
new_node.y += self.path_resolution * math.sin(theta)
new_node.path_x.append(new_node.x)
new_node.path_y.append(new_node.y)
d, _ = self.calc_distance_and_angle(new_node, to_node)
if d <= self.path_resolution:
new_node.path_x.append(to_node.x)
new_node.path_y.append(to_node.y)
new_node.x = to_node.x
new_node.y = to_node.y
new_node.parent = from_node
return new_node
def generate_final_course(self, goal_ind):
path = [[self.end.x, self.end.y]]
node = self.node_list[goal_ind]
while node.parent is not None:
path.append([node.x, node.y])
node = node.parent
path.append([node.x, node.y])
return path
def calc_dist_to_goal(self, x, y):
dx = x - self.end.x
dy = y - self.end.y
return math.hypot(dx, dy)
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(
random.uniform(self.min_rand, self.max_rand),
random.uniform(self.min_rand, self.max_rand))
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y)
return rnd
def draw_graph(self, rnd=None):
plt.clf()
# 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 rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
if self.robot_radius > 0.0:
self.plot_circle(rnd.x, rnd.y, self.robot_radius, '-r')
for node in self.node_list:
if node.parent:
plt.plot(node.path_x, node.path_y, "-g")
for (ox, oy, size) in self.obstacle_list:
self.plot_circle(ox, oy, size)
if self.play_area is not None:
plt.plot([self.play_area.xmin, self.play_area.xmax,
self.play_area.xmax, self.play_area.xmin,
self.play_area.xmin],
[self.play_area.ymin, self.play_area.ymin,
self.play_area.ymax, self.play_area.ymax,
self.play_area.ymin],
"-k")
plt.plot(self.start.x, self.start.y, "xr")
plt.plot(self.end.x, self.end.y, "xr")
plt.axis("equal")
plt.axis([self.min_rand, self.max_rand, self.min_rand, self.max_rand])
plt.grid(True)
plt.pause(0.01)
@staticmethod
def plot_circle(x, y, size, color="-b"): # pragma: no cover
deg = list(range(0, 360, 5))
deg.append(0)
xl = [x + size * math.cos(np.deg2rad(d)) for d in deg]
yl = [y + size * math.sin(np.deg2rad(d)) for d in deg]
plt.plot(xl, yl, color)
@staticmethod
def get_nearest_node_index(node_list, rnd_node):
dlist = [(node.x - rnd_node.x)**2 + (node.y - rnd_node.y)**2
for node in node_list]
minind = dlist.index(min(dlist))
return minind
@staticmethod
def check_if_outside_play_area(node, play_area):
if play_area is None:
return True # no play_area was defined, every pos should be ok
if node.x < play_area.xmin or node.x > play_area.xmax or \
node.y < play_area.ymin or node.y > play_area.ymax:
return False # outside - bad
else:
return True # inside - ok
@staticmethod
def check_collision(node, obstacleList, robot_radius):
if node is None:
return False
for (ox, oy, size) in obstacleList:
dx_list = [ox - x for x in node.path_x]
dy_list = [oy - y for y in node.path_y]
d_list = [dx * dx + dy * dy for (dx, dy) in zip(dx_list, dy_list)]
if min(d_list) <= (size+robot_radius)**2:
return False # collision
return True # safe
@staticmethod
def calc_distance_and_angle(from_node, to_node):
dx = to_node.x - from_node.x
dy = to_node.y - from_node.y
d = math.hypot(dx, dy)
theta = math.atan2(dy, dx)
return d, theta
def main(gx=6.0, gy=10.0):
print("start " + __file__)
# ====Search Path with RRT====
obstacleList = [(5, 5, 1), (3, 6, 2), (3, 8, 2), (3, 10, 2), (7, 5, 2),
(9, 5, 2), (8, 10, 1)] # [x, y, radius]
# Set Initial parameters
rrt = RRT(
start=[0, 0],
goal=[gx, gy],
rand_area=[-2, 15],
obstacle_list=obstacleList,
# play_area=[0, 10, 0, 14]
robot_radius=0.8
)
path = rrt.planning(animation=show_animation)
if path is None:
print("Cannot find path")
else:
print("found path!!")
# Draw final path
if show_animation:
rrt.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
plt.grid(True)
plt.pause(0.01) # Need for Mac
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRT/rrt.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,205 |
```python
from .sobol import i4_sobol as sobol_quasirand
``` | /content/code_sandbox/PathPlanning/RRT/sobol/__init__.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 19 |
```python
"""
Path planning Sample Code with RRT*
author: Atsushi Sakai(@Atsushi_twi)
"""
import math
import sys
import matplotlib.pyplot as plt
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from RRT.rrt import RRT
show_animation = True
class RRTStar(RRT):
"""
Class for RRT Star planning
"""
class Node(RRT.Node):
def __init__(self, x, y):
super().__init__(x, y)
self.cost = 0.0
def __init__(self,
start,
goal,
obstacle_list,
rand_area,
expand_dis=30.0,
path_resolution=1.0,
goal_sample_rate=20,
max_iter=300,
connect_circle_dist=50.0,
search_until_max_iter=False,
robot_radius=0.0):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Random Sampling Area [min,max]
"""
super().__init__(start, goal, obstacle_list, rand_area, expand_dis,
path_resolution, goal_sample_rate, max_iter,
robot_radius=robot_radius)
self.connect_circle_dist = connect_circle_dist
self.goal_node = self.Node(goal[0], goal[1])
self.search_until_max_iter = search_until_max_iter
self.node_list = []
def planning(self, animation=True):
"""
rrt star path planning
animation: flag for animation on or off .
"""
self.node_list = [self.start]
for i in range(self.max_iter):
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind], rnd,
self.expand_dis)
near_node = self.node_list[nearest_ind]
new_node.cost = near_node.cost + \
math.hypot(new_node.x-near_node.x,
new_node.y-near_node.y)
if self.check_collision(
new_node, self.obstacle_list, self.robot_radius):
near_inds = self.find_near_nodes(new_node)
node_with_updated_parent = self.choose_parent(
new_node, near_inds)
if node_with_updated_parent:
self.rewire(node_with_updated_parent, near_inds)
self.node_list.append(node_with_updated_parent)
else:
self.node_list.append(new_node)
if animation:
self.draw_graph(rnd)
if ((not self.search_until_max_iter)
and new_node): # if reaches goal
last_index = self.search_best_goal_node()
if last_index is not None:
return self.generate_final_course(last_index)
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index is not None:
return self.generate_final_course(last_index)
return None
def choose_parent(self, new_node, near_inds):
"""
Computes the cheapest point to new_node contained in the list
near_inds and set such a node as the parent of new_node.
Arguments:
--------
new_node, Node
randomly generated node with a path from its neared point
There are not coalitions between this node and th tree.
near_inds: list
Indices of indices of the nodes what are near to new_node
Returns.
------
Node, a copy of new_node
"""
if not near_inds:
return None
# search nearest cost in near_inds
costs = []
for i in near_inds:
near_node = self.node_list[i]
t_node = self.steer(near_node, new_node)
if t_node and self.check_collision(
t_node, self.obstacle_list, self.robot_radius):
costs.append(self.calc_new_cost(near_node, new_node))
else:
costs.append(float("inf")) # the cost of collision node
min_cost = min(costs)
if min_cost == float("inf"):
print("There is no good path.(min_cost is inf)")
return None
min_ind = near_inds[costs.index(min_cost)]
new_node = self.steer(self.node_list[min_ind], new_node)
new_node.cost = min_cost
return new_node
def search_best_goal_node(self):
dist_to_goal_list = [
self.calc_dist_to_goal(n.x, n.y) for n in self.node_list
]
goal_inds = [
dist_to_goal_list.index(i) for i in dist_to_goal_list
if i <= self.expand_dis
]
safe_goal_inds = []
for goal_ind in goal_inds:
t_node = self.steer(self.node_list[goal_ind], self.goal_node)
if self.check_collision(
t_node, self.obstacle_list, self.robot_radius):
safe_goal_inds.append(goal_ind)
if not safe_goal_inds:
return None
safe_goal_costs = [self.node_list[i].cost +
self.calc_dist_to_goal(self.node_list[i].x, self.node_list[i].y)
for i in safe_goal_inds]
min_cost = min(safe_goal_costs)
for i, cost in zip(safe_goal_inds, safe_goal_costs):
if cost == min_cost:
return i
return None
def find_near_nodes(self, new_node):
"""
1) defines a ball centered on new_node
2) Returns all nodes of the three that are inside this ball
Arguments:
---------
new_node: Node
new randomly generated node, without collisions between
its nearest node
Returns:
-------
list
List with the indices of the nodes inside the ball of
radius r
"""
nnode = len(self.node_list) + 1
r = self.connect_circle_dist * math.sqrt(math.log(nnode) / nnode)
# if expand_dist exists, search vertices in a range no more than
# expand_dist
if hasattr(self, 'expand_dis'):
r = min(r, self.expand_dis)
dist_list = [(node.x - new_node.x)**2 + (node.y - new_node.y)**2
for node in self.node_list]
near_inds = [dist_list.index(i) for i in dist_list if i <= r**2]
return near_inds
def rewire(self, new_node, near_inds):
"""
For each node in near_inds, this will check if it is cheaper to
arrive to them from new_node.
In such a case, this will re-assign the parent of the nodes in
near_inds to new_node.
Parameters:
----------
new_node, Node
Node randomly added which can be joined to the tree
near_inds, list of uints
A list of indices of the self.new_node which contains
nodes within a circle of a given radius.
Remark: parent is designated in choose_parent.
"""
for i in near_inds:
near_node = self.node_list[i]
edge_node = self.steer(new_node, near_node)
if not edge_node:
continue
edge_node.cost = self.calc_new_cost(new_node, near_node)
no_collision = self.check_collision(
edge_node, self.obstacle_list, self.robot_radius)
improved_cost = near_node.cost > edge_node.cost
if no_collision and improved_cost:
for node in self.node_list:
if node.parent == self.node_list[i]:
node.parent = edge_node
self.node_list[i] = edge_node
self.propagate_cost_to_leaves(self.node_list[i])
def calc_new_cost(self, from_node, to_node):
d, _ = self.calc_distance_and_angle(from_node, to_node)
return from_node.cost + d
def propagate_cost_to_leaves(self, parent_node):
for node in self.node_list:
if node.parent == parent_node:
node.cost = self.calc_new_cost(parent_node, node)
self.propagate_cost_to_leaves(node)
def main():
print("Start " + __file__)
# ====Search Path with RRT====
obstacle_list = [
(5, 5, 1),
(3, 6, 2),
(3, 8, 2),
(3, 10, 2),
(7, 5, 2),
(9, 5, 2),
(8, 10, 1),
(6, 12, 1),
] # [x,y,size(radius)]
# Set Initial parameters
rrt_star = RRTStar(
start=[0, 0],
goal=[6, 10],
rand_area=[-2, 15],
obstacle_list=obstacle_list,
expand_dis=1,
robot_radius=0.8)
path = rrt_star.planning(animation=show_animation)
if path is None:
print("Cannot find path")
else:
print("found path!!")
# Draw final path
if show_animation:
rrt_star.draw_graph()
plt.plot([x for (x, y) in path], [y for (x, y) in path], 'r--')
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/RRTStar/rrt_star.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,051 |
```python
"""
Breadth-First grid planning
author: Erwin Lejeune (@spida_rwin)
See Wikipedia article (path_to_url
"""
import math
import matplotlib.pyplot as plt
show_animation = True
class BreadthFirstSearchPlanner:
def __init__(self, ox, oy, reso, rr):
"""
Initialize grid map for bfs planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.reso = reso
self.rr = rr
self.calc_obstacle_map(ox, oy)
self.motion = self.get_motion_model()
class Node:
def __init__(self, x, y, cost, parent_index, parent):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
self.parent = parent
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
Breadth First search based planning
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
nstart = self.Node(self.calc_xyindex(sx, self.minx),
self.calc_xyindex(sy, self.miny), 0.0, -1, None)
ngoal = self.Node(self.calc_xyindex(gx, self.minx),
self.calc_xyindex(gy, self.miny), 0.0, -1, None)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(nstart)] = nstart
while True:
if len(open_set) == 0:
print("Open set is empty..")
break
current = open_set.pop(list(open_set.keys())[0])
c_id = self.calc_grid_index(current)
closed_set[c_id] = current
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current.x, self.minx),
self.calc_grid_position(current.y, self.miny), "xc")
# 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 len(closed_set.keys()) % 10 == 0:
plt.pause(0.001)
if current.x == ngoal.x and current.y == ngoal.y:
print("Find goal")
ngoal.parent_index = current.parent_index
ngoal.cost = current.cost
break
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2], c_id, None)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if (n_id not in closed_set) and (n_id not in open_set):
node.parent = current
open_set[n_id] = node
rx, ry = self.calc_final_path(ngoal, closed_set)
return rx, ry
def calc_final_path(self, ngoal, closedset):
# generate final course
rx, ry = [self.calc_grid_position(ngoal.x, self.minx)], [
self.calc_grid_position(ngoal.y, self.miny)]
n = closedset[ngoal.parent_index]
while n is not None:
rx.append(self.calc_grid_position(n.x, self.minx))
ry.append(self.calc_grid_position(n.y, self.miny))
n = n.parent
return rx, ry
def calc_grid_position(self, index, minp):
"""
calc grid position
:param index:
:param minp:
:return:
"""
pos = index * self.reso + minp
return pos
def calc_xyindex(self, position, min_pos):
return round((position - min_pos) / self.reso)
def calc_grid_index(self, node):
return (node.y - self.miny) * self.xwidth + (node.x - self.minx)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.minx)
py = self.calc_grid_position(node.y, self.miny)
if px < self.minx:
return False
elif py < self.miny:
return False
elif px >= self.maxx:
return False
elif py >= self.maxy:
return False
# collision check
if self.obmap[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.minx = round(min(ox))
self.miny = round(min(oy))
self.maxx = round(max(ox))
self.maxy = round(max(oy))
print("min_x:", self.minx)
print("min_y:", self.miny)
print("max_x:", self.maxx)
print("max_y:", self.maxy)
self.xwidth = round((self.maxx - self.minx) / self.reso)
self.ywidth = round((self.maxy - self.miny) / self.reso)
print("x_width:", self.xwidth)
print("y_width:", self.ywidth)
# obstacle map generation
self.obmap = [[False for _ in range(self.ywidth)]
for _ in range(self.xwidth)]
for ix in range(self.xwidth):
x = self.calc_grid_position(ix, self.minx)
for iy in range(self.ywidth):
y = self.calc_grid_position(iy, self.miny)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obmap[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [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: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
bfs = BreadthFirstSearchPlanner(ox, oy, grid_size, robot_radius)
rx, ry = bfs.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.01)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/PathPlanning/BreadthFirstSearch/breadth_first_search.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,931 |
```python
"""
Licensing:
This code is distributed under the MIT license.
Authors:
Original FORTRAN77 version of i4_sobol by Bennett Fox.
MATLAB version by John Burkardt.
PYTHON version by Corrado Chisari
Original Python version of is_prime by Corrado Chisari
Original MATLAB versions of other functions by John Burkardt.
PYTHON versions by Corrado Chisari
Original code is available at
path_to_url~jburkardt/py_src/sobol/sobol.html
Note: the i4 prefix means that the function takes a numeric argument or
returns a number which is interpreted inside the function as a 4
byte integer
Note: the r4 prefix means that the function takes a numeric argument or
returns a number which is interpreted inside the function as a 4
byte float
"""
import math
import sys
import numpy as np
atmost = None
dim_max = None
dim_num_save = None
initialized = None
lastq = None
log_max = None
maxcol = None
poly = None
recipd = None
seed_save = None
v = None
def i4_bit_hi1(n):
"""
I4_BIT_HI1 returns the position of the high 1 bit base 2 in an I4.
Discussion:
An I4 is an integer ( kind = 4 ) value.
Example:
N Binary Hi 1
---- -------- ----
0 0 0
1 1 1
2 10 2
3 11 2
4 100 3
5 101 3
6 110 3
7 111 3
8 1000 4
9 1001 4
10 1010 4
11 1011 4
12 1100 4
13 1101 4
14 1110 4
15 1111 4
16 10000 5
17 10001 5
1023 1111111111 10
1024 10000000000 11
1025 10000000001 11
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
26 October 2014
Author:
John Burkardt
Parameters:
Input, integer N, the integer to be measured.
N should be nonnegative. If N is nonpositive, the function
will always be 0.
Output, integer BIT, the position of the highest bit.
"""
i = n
bit = 0
while True:
if i <= 0:
break
bit = bit + 1
i = i // 2
return bit
def i4_bit_lo0(n):
"""
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an I4.
Discussion:
An I4 is an integer ( kind = 4 ) value.
Example:
N Binary Lo 0
---- -------- ----
0 0 1
1 1 2
2 10 1
3 11 3
4 100 1
5 101 2
6 110 1
7 111 4
8 1000 1
9 1001 2
10 1010 1
11 1011 3
12 1100 1
13 1101 2
14 1110 1
15 1111 5
16 10000 1
17 10001 2
1023 1111111111 11
1024 10000000000 1
1025 10000000001 2
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
08 February 2018
Author:
John Burkardt
Parameters:
Input, integer N, the integer to be measured.
N should be nonnegative.
Output, integer BIT, the position of the low 1 bit.
"""
bit = 0
i = n
while True:
bit = bit + 1
i2 = i // 2
if i == 2 * i2:
break
i = i2
return bit
def i4_sobol_generate(m, n, skip):
"""
I4_SOBOL_GENERATE generates a Sobol dataset.
Licensing:
This code is distributed under the MIT license.
Modified:
22 February 2011
Author:
Original MATLAB version by John Burkardt.
PYTHON version by Corrado Chisari
Parameters:
Input, integer M, the spatial dimension.
Input, integer N, the number of points to generate.
Input, integer SKIP, the number of initial points to skip.
Output, real R(M,N), the points.
"""
r = np.zeros((m, n))
for j in range(1, n + 1):
seed = skip + j - 2
[r[0:m, j - 1], seed] = i4_sobol(m, seed)
return r
def i4_sobol(dim_num, seed):
"""
I4_SOBOL generates a new quasirandom Sobol vector with each call.
Discussion:
The routine adapts the ideas of Antonov and Saleev.
Licensing:
This code is distributed under the MIT license.
Modified:
22 February 2011
Author:
Original FORTRAN77 version by Bennett Fox.
MATLAB version by John Burkardt.
PYTHON version by Corrado Chisari
Reference:
Antonov, Saleev,
USSR Computational Mathematics and Mathematical Physics,
olume 19, 19, pages 252 - 256.
Paul Bratley, Bennett Fox,
Algorithm 659:
Implementing Sobol's Quasirandom Sequence Generator,
ACM Transactions on Mathematical Software,
Volume 14, Number 1, pages 88-100, 1988.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Ilya Sobol,
USSR Computational Mathematics and Mathematical Physics,
Volume 16, pages 236-242, 1977.
Ilya Sobol, Levitan,
The Production of Points Uniformly Distributed in a Multidimensional
Cube (in Russian),
Preprint IPM Akad. Nauk SSSR,
Number 40, Moscow 1976.
Parameters:
Input, integer DIM_NUM, the number of spatial dimensions.
DIM_NUM must satisfy 1 <= DIM_NUM <= 40.
Input/output, integer SEED, the "seed" for the sequence.
This is essentially the index in the sequence of the quasirandom
value to be generated. On output, SEED has been set to the
appropriate next value, usually simply SEED+1.
If SEED is less than 0 on input, it is treated as though it were 0.
An input value of 0 requests the first (0-th) element of the sequence.
Output, real QUASI(DIM_NUM), the next quasirandom vector.
"""
global atmost
global dim_max
global dim_num_save
global initialized
global lastq
global log_max
global maxcol
global poly
global recipd
global seed_save
global v
if not initialized or dim_num != dim_num_save:
initialized = 1
dim_max = 40
dim_num_save = -1
log_max = 30
seed_save = -1
#
# Initialize (part of) V.
#
v = np.zeros((dim_max, log_max))
v[0:40, 0] = np.transpose([
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
])
v[2:40, 1] = np.transpose([
1, 3, 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, 1, 3, 1, 3,
3, 1, 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, 1, 3, 1, 3
])
v[3:40, 2] = np.transpose([
7, 5, 1, 3, 3, 7, 5, 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, 5, 3, 3, 1, 7,
5, 1, 3, 3, 7, 5, 1, 1, 5, 7, 7, 5, 1, 3, 3
])
v[5:40, 3] = np.transpose([
1, 7, 9, 13, 11, 1, 3, 7, 9, 5, 13, 13, 11, 3, 15, 5, 3, 15, 7, 9,
13, 9, 1, 11, 7, 5, 15, 1, 15, 11, 5, 3, 1, 7, 9
])
v[7:40, 4] = np.transpose([
9, 3, 27, 15, 29, 21, 23, 19, 11, 25, 7, 13, 17, 1, 25, 29, 3, 31,
11, 5, 23, 27, 19, 21, 5, 1, 17, 13, 7, 15, 9, 31, 9
])
v[13:40, 5] = np.transpose([
37, 33, 7, 5, 11, 39, 63, 27, 17, 15, 23, 29, 3, 21, 13, 31, 25, 9,
49, 33, 19, 29, 11, 19, 27, 15, 25
])
v[19:40, 6] = np.transpose([
13, 33, 115, 41, 79, 17, 29, 119, 75, 73, 105, 7, 59, 65, 21, 3,
113, 61, 89, 45, 107
])
v[37:40, 7] = np.transpose([7, 23, 39])
#
# Set POLY.
#
poly = [
1, 3, 7, 11, 13, 19, 25, 37, 59, 47, 61, 55, 41, 67, 97, 91, 109,
103, 115, 131, 193, 137, 145, 143, 241, 157, 185, 167, 229, 171,
213, 191, 253, 203, 211, 239, 247, 285, 369, 299
]
atmost = 2**log_max - 1
#
# Find the number of bits in ATMOST.
#
maxcol = i4_bit_hi1(atmost)
#
# Initialize row 1 of V.
#
v[0, 0:maxcol] = 1
# Things to do only if the dimension changed.
if dim_num != dim_num_save:
#
# Check parameters.
#
if (dim_num < 1 or dim_max < dim_num):
print('I4_SOBOL - Fatal error!')
print(' The spatial dimension DIM_NUM should satisfy:')
print(' 1 <= DIM_NUM <= %d' % dim_max)
print(' But this input value is DIM_NUM = %d' % dim_num)
return None
dim_num_save = dim_num
#
# Initialize the remaining rows of V.
#
for i in range(2, dim_num + 1):
#
# The bits of the integer POLY(I) gives the form of polynomial
# I.
#
# Find the degree of polynomial I from binary encoding.
#
j = poly[i - 1]
m = 0
while True:
j = math.floor(j / 2.)
if (j <= 0):
break
m = m + 1
#
# Expand this bit pattern to separate components of the logical
# array INCLUD.
#
j = poly[i - 1]
includ = np.zeros(m)
for k in range(m, 0, -1):
j2 = math.floor(j / 2.)
includ[k - 1] = (j != 2 * j2)
j = j2
#
# Calculate the remaining elements of row I as explained
# in Bratley and Fox, section 2.
#
for j in range(m + 1, maxcol + 1):
newv = v[i - 1, j - m - 1]
l_var = 1
for k in range(1, m + 1):
l_var = 2 * l_var
if (includ[k - 1]):
newv = np.bitwise_xor(
int(newv), int(l_var * v[i - 1, j - k - 1]))
v[i - 1, j - 1] = newv
#
# Multiply columns of V by appropriate power of 2.
#
l_var = 1
for j in range(maxcol - 1, 0, -1):
l_var = 2 * l_var
v[0:dim_num, j - 1] = v[0:dim_num, j - 1] * l_var
#
# RECIPD is 1/(common denominator of the elements in V).
#
recipd = 1.0 / (2 * l_var)
lastq = np.zeros(dim_num)
seed = int(math.floor(seed))
if (seed < 0):
seed = 0
if (seed == 0):
l_var = 1
lastq = np.zeros(dim_num)
elif (seed == seed_save + 1):
#
# Find the position of the right-hand zero in SEED.
#
l_var = i4_bit_lo0(seed)
elif (seed <= seed_save):
seed_save = 0
lastq = np.zeros(dim_num)
for seed_temp in range(int(seed_save), int(seed)):
l_var = i4_bit_lo0(seed_temp)
for i in range(1, dim_num + 1):
lastq[i - 1] = np.bitwise_xor(
int(lastq[i - 1]), int(v[i - 1, l_var - 1]))
l_var = i4_bit_lo0(seed)
elif (seed_save + 1 < seed):
for seed_temp in range(int(seed_save + 1), int(seed)):
l_var = i4_bit_lo0(seed_temp)
for i in range(1, dim_num + 1):
lastq[i - 1] = np.bitwise_xor(
int(lastq[i - 1]), int(v[i - 1, l_var - 1]))
l_var = i4_bit_lo0(seed)
#
# Check that the user is not calling too many times!
#
if maxcol < l_var:
print('I4_SOBOL - Fatal error!')
print(' Too many calls!')
print(' MAXCOL = %d\n' % maxcol)
print(' L = %d\n' % l_var)
return None
#
# Calculate the new components of QUASI.
#
quasi = np.zeros(dim_num)
for i in range(1, dim_num + 1):
quasi[i - 1] = lastq[i - 1] * recipd
lastq[i - 1] = np.bitwise_xor(
int(lastq[i - 1]), int(v[i - 1, l_var - 1]))
seed_save = seed
seed = seed + 1
return [quasi, seed]
def i4_uniform_ab(a, b, seed):
"""
I4_UNIFORM_AB returns a scaled pseudorandom I4.
Discussion:
The pseudorandom number will be scaled to be uniformly distributed
between A and B.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
05 April 2013
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Second Edition,
Springer, 1987,
ISBN: 0387964673,
LC: QA76.9.C65.B73.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, December 1986, pages 362-376.
Pierre L'Ecuyer,
Random Number Generation,
in Handbook of Simulation,
edited by Jerry Banks,
Wiley, 1998,
ISBN: 0471134031,
LC: T57.62.H37.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, Number 2, 1969, pages 136-143.
Parameters:
Input, integer A, B, the minimum and maximum acceptable values.
Input, integer SEED, a seed for the random number generator.
Output, integer C, the randomly chosen integer.
Output, integer SEED, the updated seed.
"""
i4_huge = 2147483647
seed = int(seed)
seed = (seed % i4_huge)
if seed < 0:
seed = seed + i4_huge
if seed == 0:
print('')
print('I4_UNIFORM_AB - Fatal error!')
print(' Input SEED = 0!')
sys.exit('I4_UNIFORM_AB - Fatal error!')
k = (seed // 127773)
seed = 167 * (seed - k * 127773) - k * 2836
if seed < 0:
seed = seed + i4_huge
r = seed * 4.656612875E-10
#
# Scale R to lie between A-0.5 and B+0.5.
#
a = round(a)
b = round(b)
r = (1.0 - r) * (min(a, b) - 0.5) \
+ r * (max(a, b) + 0.5)
#
# Use rounding to convert R to an integer between A and B.
#
value = round(r)
value = max(value, min(a, b))
value = min(value, max(a, b))
value = int(value)
return value, seed
def prime_ge(n):
"""
PRIME_GE returns the smallest prime greater than or equal to N.
Example:
N PRIME_GE
-10 2
1 2
2 2
3 3
4 5
5 5
6 7
7 7
8 11
9 11
10 11
Licensing:
This code is distributed under the MIT license.
Modified:
22 February 2011
Author:
Original MATLAB version by John Burkardt.
PYTHON version by Corrado Chisari
Parameters:
Input, integer N, the number to be bounded.
Output, integer P, the smallest prime number that is greater
than or equal to N.
"""
p = max(math.ceil(n), 2)
while not isprime(p):
p = p + 1
return p
def isprime(n):
"""
IS_PRIME returns True if N is a prime number, False otherwise
Licensing:
This code is distributed under the MIT license.
Modified:
22 February 2011
Author:
Corrado Chisari
Parameters:
Input, integer N, the number to be checked.
Output, boolean value, True or False
"""
if n != int(n) or n < 1:
return False
p = 2
while p < n:
if n % p == 0:
return False
p += 1
return True
def r4_uniform_01(seed):
"""
R4_UNIFORM_01 returns a unit pseudorandom R4.
Discussion:
This routine implements the recursion
seed = 167 * seed mod ( 2^31 - 1 )
r = seed / ( 2^31 - 1 )
The integer arithmetic never requires more than 32 bits,
including a sign bit.
If the initial seed is 12345, then the first three computations are
Input Output R4_UNIFORM_01
SEED SEED
12345 207482415 0.096616
207482415 1790989824 0.833995
1790989824 2035175616 0.947702
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
04 April 2013
Author:
John Burkardt
Reference:
Paul Bratley, Bennett Fox, Linus Schrage,
A Guide to Simulation,
Second Edition,
Springer, 1987,
ISBN: 0387964673,
LC: QA76.9.C65.B73.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, December 1986, pages 362-376.
Pierre L'Ecuyer,
Random Number Generation,
in Handbook of Simulation,
edited by Jerry Banks,
Wiley, 1998,
ISBN: 0471134031,
LC: T57.62.H37.
Peter Lewis, Allen Goodman, James Miller,
A Pseudo-Random Number Generator for the System/360,
IBM Systems Journal,
Volume 8, Number 2, 1969, pages 136-143.
Parameters:
Input, integer SEED, the integer "seed" used to generate
the output random number. SEED should not be 0.
Output, real R, a random value between 0 and 1.
Output, integer SEED, the updated seed. This would
normally be used as the input seed on the next call.
"""
i4_huge = 2147483647
if (seed == 0):
print('')
print('R4_UNIFORM_01 - Fatal error!')
print(' Input SEED = 0!')
sys.exit('R4_UNIFORM_01 - Fatal error!')
seed = (seed % i4_huge)
if seed < 0:
seed = seed + i4_huge
k = (seed // 127773)
seed = 167 * (seed - k * 127773) - k * 2836
if seed < 0:
seed = seed + i4_huge
r = seed * 4.656612875E-10
return r, seed
def r8mat_write(filename, m, n, a):
"""
R8MAT_WRITE writes an R8MAT to a file.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
12 October 2014
Author:
John Burkardt
Parameters:
Input, string FILENAME, the name of the output file.
Input, integer M, the number of rows in A.
Input, integer N, the number of columns in A.
Input, real A(M,N), the matrix.
"""
with open(filename, 'w') as output:
for i in range(0, m):
for j in range(0, n):
s = ' %g' % (a[i, j])
output.write(s)
output.write('\n')
def tau_sobol(dim_num):
"""
TAU_SOBOL defines favorable starting seeds for Sobol sequences.
Discussion:
For spatial dimensions 1 through 13, this routine returns
a "favorable" value TAU by which an appropriate starting point
in the Sobol sequence can be determined.
These starting points have the form N = 2**K, where
for integration problems, it is desirable that
TAU + DIM_NUM - 1 <= K
while for optimization problems, it is desirable that
TAU < K.
Licensing:
This code is distributed under the MIT license.
Modified:
22 February 2011
Author:
Original FORTRAN77 version by Bennett Fox.
MATLAB version by John Burkardt.
PYTHON version by Corrado Chisari
Reference:
IA Antonov, VM Saleev,
USSR Computational Mathematics and Mathematical Physics,
Volume 19, 19, pages 252 - 256.
Paul Bratley, Bennett Fox,
Algorithm 659:
Implementing Sobol's Quasirandom Sequence Generator,
ACM Transactions on Mathematical Software,
Volume 14, Number 1, pages 88-100, 1988.
Bennett Fox,
Algorithm 647:
Implementation and Relative Efficiency of Quasirandom
Sequence Generators,
ACM Transactions on Mathematical Software,
Volume 12, Number 4, pages 362-376, 1986.
Stephen Joe, Frances Kuo
Remark on Algorithm 659:
Implementing Sobol's Quasirandom Sequence Generator,
ACM Transactions on Mathematical Software,
Volume 29, Number 1, pages 49-57, March 2003.
Ilya Sobol,
USSR Computational Mathematics and Mathematical Physics,
Volume 16, pages 236-242, 1977.
Ilya Sobol, YL Levitan,
The Production of Points Uniformly Distributed in a Multidimensional
Cube (in Russian),
Preprint IPM Akad. Nauk SSSR,
Number 40, Moscow 1976.
Parameters:
Input, integer DIM_NUM, the spatial dimension. Only values
of 1 through 13 will result in useful responses.
Output, integer TAU, the value TAU.
"""
dim_max = 13
tau_table = [0, 0, 1, 3, 5, 8, 11, 15, 19, 23, 27, 31, 35]
if 1 <= dim_num <= dim_max:
tau = tau_table[dim_num]
else:
tau = -1
return tau
``` | /content/code_sandbox/PathPlanning/RRT/sobol/sobol.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 6,458 |
```python
"""
Inverse kinematics of a two-joint arm
Left-click the plot to set the goal position of the end effector
Author: Daniel Ingram (daniel-s-ingram)
Atsushi Sakai (@Atsushi_twi)
Ref: P. I. Corke, "Robotics, Vision & Control", Springer 2017,
ISBN 978-3-319-54413-7 p102
- [Robotics, Vision and Control]
(path_to_url
"""
import matplotlib.pyplot as plt
import numpy as np
import math
from utils.angle import angle_mod
# Simulation parameters
Kp = 15
dt = 0.01
# Link lengths
l1 = l2 = 1
# Set initial goal position to the initial end-effector position
x = 2
y = 0
show_animation = True
if show_animation:
plt.ion()
def two_joint_arm(GOAL_TH=0.0, theta1=0.0, theta2=0.0):
"""
Computes the inverse kinematics for a planar 2DOF arm
When out of bounds, rewrite x and y with last correct values
"""
global x, y
x_prev, y_prev = None, None
while True:
try:
if x is not None and y is not None:
x_prev = x
y_prev = y
if np.hypot(x, y) > (l1 + l2):
theta2_goal = 0
else:
theta2_goal = np.arccos(
(x**2 + y**2 - l1**2 - l2**2) / (2 * l1 * l2))
tmp = math.atan2(l2 * np.sin(theta2_goal),
(l1 + l2 * np.cos(theta2_goal)))
theta1_goal = math.atan2(y, x) - tmp
if theta1_goal < 0:
theta2_goal = -theta2_goal
tmp = math.atan2(l2 * np.sin(theta2_goal),
(l1 + l2 * np.cos(theta2_goal)))
theta1_goal = math.atan2(y, x) - tmp
theta1 = theta1 + Kp * ang_diff(theta1_goal, theta1) * dt
theta2 = theta2 + Kp * ang_diff(theta2_goal, theta2) * dt
except ValueError as e:
print("Unreachable goal"+e)
except TypeError:
x = x_prev
y = y_prev
wrist = plot_arm(theta1, theta2, x, y)
# check goal
d2goal = None
if x is not None and y is not None:
d2goal = np.hypot(wrist[0] - x, wrist[1] - y)
if abs(d2goal) < GOAL_TH and x is not None:
return theta1, theta2
def plot_arm(theta1, theta2, target_x, target_y): # pragma: no cover
shoulder = np.array([0, 0])
elbow = shoulder + np.array([l1 * np.cos(theta1), l1 * np.sin(theta1)])
wrist = elbow + \
np.array([l2 * np.cos(theta1 + theta2), l2 * np.sin(theta1 + theta2)])
if show_animation:
plt.cla()
plt.plot([shoulder[0], elbow[0]], [shoulder[1], elbow[1]], 'k-')
plt.plot([elbow[0], wrist[0]], [elbow[1], wrist[1]], 'k-')
plt.plot(shoulder[0], shoulder[1], 'ro')
plt.plot(elbow[0], elbow[1], 'ro')
plt.plot(wrist[0], wrist[1], 'ro')
plt.plot([wrist[0], target_x], [wrist[1], target_y], 'g--')
plt.plot(target_x, target_y, 'g*')
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.show()
plt.pause(dt)
return wrist
def ang_diff(theta1, theta2):
# Returns the difference between two angles in the range -pi to +pi
return angle_mod(theta1 - theta2)
def click(event): # pragma: no cover
global x, y
x = event.xdata
y = event.ydata
def animation():
from random import random
global x, y
theta1 = theta2 = 0.0
for i in range(5):
x = 2.0 * random() - 1.0
y = 2.0 * random() - 1.0
theta1, theta2 = two_joint_arm(
GOAL_TH=0.01, theta1=theta1, theta2=theta2)
def main(): # pragma: no cover
fig = plt.figure()
fig.canvas.mpl_connect("button_press_event", click)
# for stopping simulation with the esc key.
fig.canvas.mpl_connect('key_release_event', lambda event: [
exit(0) if event.key == 'escape' else None])
two_joint_arm()
if __name__ == "__main__":
# animation()
main()
``` | /content/code_sandbox/ArmNavigation/two_joint_arm_to_point_control/two_joint_arm_to_point_control.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,162 |
```python
"""
Inverse Kinematics for an n-link arm in 3D
Author: Takayuki Murooka (takayuki5168)
"""
import math
from NLinkArm3d import NLinkArm
import random
def random_val(min_val, max_val):
return min_val + random.random() * (max_val - min_val)
def main():
print("Start solving Inverse Kinematics 10 times")
# init NLinkArm with Denavit-Hartenberg parameters of PR2
n_link_arm = NLinkArm([[0., -math.pi / 2, .1, 0.],
[math.pi / 2, math.pi / 2, 0., 0.],
[0., -math.pi / 2, 0., .4],
[0., math.pi / 2, 0., 0.],
[0., -math.pi / 2, 0., .321],
[0., math.pi / 2, 0., 0.],
[0., 0., 0., 0.]])
# execute IK 10 times
for _ in range(10):
n_link_arm.inverse_kinematics([random_val(-0.5, 0.5),
random_val(-0.5, 0.5),
random_val(-0.5, 0.5),
random_val(-0.5, 0.5),
random_val(-0.5, 0.5),
random_val(-0.5, 0.5)], plot=True)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/ArmNavigation/n_joint_arm_3d/random_inverse_kinematics.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 350 |
```python
"""
Forward Kinematics for an n-link arm in 3D
Author: Takayuki Murooka (takayuki5168)
"""
import math
from NLinkArm3d import NLinkArm
import random
def random_val(min_val, max_val):
return min_val + random.random() * (max_val - min_val)
def main():
print("Start solving Forward Kinematics 10 times")
# init NLinkArm with Denavit-Hartenberg parameters of PR2
n_link_arm = NLinkArm([[0., -math.pi / 2, .1, 0.],
[math.pi / 2, math.pi / 2, 0., 0.],
[0., -math.pi / 2, 0., .4],
[0., math.pi / 2, 0., 0.],
[0., -math.pi / 2, 0., .321],
[0., math.pi / 2, 0., 0.],
[0., 0., 0., 0.]])
# execute FK 10 times
for _ in range(10):
n_link_arm.set_joint_angles(
[random_val(-1, 1) for _ in range(len(n_link_arm.link_list))])
n_link_arm.forward_kinematics(plot=True)
if __name__ == "__main__":
main()
``` | /content/code_sandbox/ArmNavigation/n_joint_arm_3d/random_forward_kinematics.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 301 |
```python
"""
RRT* path planner for a seven joint arm
Author: Mahyar Abdeetedal (mahyaret)
"""
import math
import random
import numpy as np
import matplotlib.pyplot as plt
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.parent))
from n_joint_arm_3d.NLinkArm3d import NLinkArm
show_animation = True
verbose = False
class RobotArm(NLinkArm):
def get_points(self, joint_angle_list):
self.set_joint_angles(joint_angle_list)
x_list = []
y_list = []
z_list = []
trans = np.identity(4)
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
for i in range(len(self.link_list)):
trans = np.dot(trans, self.link_list[i].transformation_matrix())
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
return x_list, y_list, z_list
class RRTStar:
"""
Class for RRT Star planning
"""
class Node:
def __init__(self, x):
self.x = x
self.parent = None
self.cost = 0.0
def __init__(self, start, goal, robot, obstacle_list, rand_area,
expand_dis=.30,
path_resolution=.1,
goal_sample_rate=20,
max_iter=300,
connect_circle_dist=50.0
):
"""
Setting Parameter
start:Start Position [q1,...,qn]
goal:Goal Position [q1,...,qn]
obstacleList:obstacle Positions [[x,y,z,size],...]
randArea:Random Sampling Area [min,max]
"""
self.start = self.Node(start)
self.end = self.Node(goal)
self.dimension = len(start)
self.min_rand = rand_area[0]
self.max_rand = rand_area[1]
self.expand_dis = expand_dis
self.path_resolution = path_resolution
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.robot = robot
self.obstacle_list = obstacle_list
self.connect_circle_dist = connect_circle_dist
self.goal_node = self.Node(goal)
self.node_list = []
if show_animation:
self.ax = plt.axes(projection='3d')
def planning(self, animation=False, search_until_max_iter=False):
"""
rrt star path planning
animation: flag for animation on or off
search_until_max_iter: search until max iteration for path
improving or not
"""
self.node_list = [self.start]
for i in range(self.max_iter):
if verbose:
print("Iter:", i, ", number of nodes:", len(self.node_list))
rnd = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd)
new_node = self.steer(self.node_list[nearest_ind],
rnd,
self.expand_dis)
if self.check_collision(new_node, self.robot, self.obstacle_list):
near_inds = self.find_near_nodes(new_node)
new_node = self.choose_parent(new_node, near_inds)
if new_node:
self.node_list.append(new_node)
self.rewire(new_node, near_inds)
if animation and i % 5 == 0 and self.dimension <= 3:
self.draw_graph(rnd)
if (not search_until_max_iter) and new_node:
last_index = self.search_best_goal_node()
if last_index is not None:
return self.generate_final_course(last_index)
if verbose:
print("reached max iteration")
last_index = self.search_best_goal_node()
if last_index is not None:
return self.generate_final_course(last_index)
return None
def choose_parent(self, new_node, near_inds):
if not near_inds:
return None
# search nearest cost in near_inds
costs = []
for i in near_inds:
near_node = self.node_list[i]
t_node = self.steer(near_node, new_node)
if t_node and self.check_collision(t_node,
self.robot,
self.obstacle_list):
costs.append(self.calc_new_cost(near_node, new_node))
else:
costs.append(float("inf")) # the cost of collision node
min_cost = min(costs)
if min_cost == float("inf"):
print("There is no good path.(min_cost is inf)")
return None
min_ind = near_inds[costs.index(min_cost)]
new_node = self.steer(self.node_list[min_ind], new_node)
new_node.parent = self.node_list[min_ind]
new_node.cost = min_cost
return new_node
def search_best_goal_node(self):
dist_to_goal_list = [self.calc_dist_to_goal(n.x)
for n in self.node_list]
goal_inds = [dist_to_goal_list.index(i)
for i in dist_to_goal_list if i <= self.expand_dis]
safe_goal_inds = []
for goal_ind in goal_inds:
t_node = self.steer(self.node_list[goal_ind], self.goal_node)
if self.check_collision(t_node, self.robot, self.obstacle_list):
safe_goal_inds.append(goal_ind)
if not safe_goal_inds:
return None
min_cost = min([self.node_list[i].cost for i in safe_goal_inds])
for i in safe_goal_inds:
if self.node_list[i].cost == min_cost:
return i
return None
def find_near_nodes(self, new_node):
nnode = len(self.node_list) + 1
r = self.connect_circle_dist * math.sqrt(math.log(nnode) / nnode)
# if expand_dist exists, search vertices in
# a range no more than expand_dist
if hasattr(self, 'expand_dis'):
r = min(r, self.expand_dis)
dist_list = [np.sum((np.array(node.x) - np.array(new_node.x)) ** 2)
for node in self.node_list]
near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2]
return near_inds
def rewire(self, new_node, near_inds):
for i in near_inds:
near_node = self.node_list[i]
edge_node = self.steer(new_node, near_node)
if not edge_node:
continue
edge_node.cost = self.calc_new_cost(new_node, near_node)
no_collision = self.check_collision(edge_node,
self.robot,
self.obstacle_list)
improved_cost = near_node.cost > edge_node.cost
if no_collision and improved_cost:
self.node_list[i] = edge_node
self.propagate_cost_to_leaves(new_node)
def calc_new_cost(self, from_node, to_node):
d, _, _ = self.calc_distance_and_angle(from_node, to_node)
return from_node.cost + d
def propagate_cost_to_leaves(self, parent_node):
for node in self.node_list:
if node.parent == parent_node:
node.cost = self.calc_new_cost(parent_node, node)
self.propagate_cost_to_leaves(node)
def generate_final_course(self, goal_ind):
path = [self.end.x]
node = self.node_list[goal_ind]
while node.parent is not None:
path.append(node.x)
node = node.parent
path.append(node.x)
reversed(path)
return path
def calc_dist_to_goal(self, x):
distance = np.linalg.norm(np.array(x) - np.array(self.end.x))
return distance
def get_random_node(self):
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(np.random.uniform(self.min_rand,
self.max_rand,
self.dimension))
else: # goal point sampling
rnd = self.Node(self.end.x)
return rnd
def steer(self, from_node, to_node, extend_length=float("inf")):
new_node = self.Node(list(from_node.x))
d, phi, theta = self.calc_distance_and_angle(new_node, to_node)
new_node.path_x = [list(new_node.x)]
if extend_length > d:
extend_length = d
n_expand = math.floor(extend_length / self.path_resolution)
start, end = np.array(from_node.x), np.array(to_node.x)
v = end - start
u = v / (np.sqrt(np.sum(v ** 2)))
for _ in range(n_expand):
new_node.x += u * self.path_resolution
new_node.path_x.append(list(new_node.x))
d, _, _ = self.calc_distance_and_angle(new_node, to_node)
if d <= self.path_resolution:
new_node.path_x.append(list(to_node.x))
new_node.parent = from_node
return new_node
def draw_graph(self, rnd=None):
plt.cla()
self.ax.axis([-1, 1, -1, 1, -1, 1])
self.ax.set_zlim(0, 1)
self.ax.grid(True)
for (ox, oy, oz, size) in self.obstacle_list:
self.plot_sphere(self.ax, ox, oy, oz, size=size)
if self.dimension > 3:
return self.ax
if rnd is not None:
self.ax.plot([rnd.x[0]], [rnd.x[1]], [rnd.x[2]], "^k")
for node in self.node_list:
if node.parent:
path = np.array(node.path_x)
plt.plot(path[:, 0], path[:, 1], path[:, 2], "-g")
self.ax.plot([self.start.x[0]], [self.start.x[1]],
[self.start.x[2]], "xr")
self.ax.plot([self.end.x[0]], [self.end.x[1]], [self.end.x[2]], "xr")
plt.pause(0.01)
return self.ax
@staticmethod
def get_nearest_node_index(node_list, rnd_node):
dlist = [np.sum((np.array(node.x) - np.array(rnd_node.x))**2)
for node in node_list]
minind = dlist.index(min(dlist))
return minind
@staticmethod
def plot_sphere(ax, x, y, z, size=1, color="k"):
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
xl = x+size*np.cos(u)*np.sin(v)
yl = y+size*np.sin(u)*np.sin(v)
zl = z+size*np.cos(v)
ax.plot_wireframe(xl, yl, zl, color=color)
@staticmethod
def calc_distance_and_angle(from_node, to_node):
dx = to_node.x[0] - from_node.x[0]
dy = to_node.x[1] - from_node.x[1]
dz = to_node.x[2] - from_node.x[2]
d = np.sqrt(np.sum((np.array(to_node.x) - np.array(from_node.x))**2))
phi = math.atan2(dy, dx)
theta = math.atan2(math.hypot(dx, dy), dz)
return d, phi, theta
@staticmethod
def calc_distance_and_angle2(from_node, to_node):
dx = to_node.x[0] - from_node.x[0]
dy = to_node.x[1] - from_node.x[1]
dz = to_node.x[2] - from_node.x[2]
d = math.sqrt(dx**2 + dy**2 + dz**2)
phi = math.atan2(dy, dx)
theta = math.atan2(math.hypot(dx, dy), dz)
return d, phi, theta
@staticmethod
def check_collision(node, robot, obstacleList):
if node is None:
return False
for (ox, oy, oz, size) in obstacleList:
for x in node.path_x:
x_list, y_list, z_list = robot.get_points(x)
dx_list = [ox - x_point for x_point in x_list]
dy_list = [oy - y_point for y_point in y_list]
dz_list = [oz - z_point for z_point in z_list]
d_list = [dx * dx + dy * dy + dz * dz
for (dx, dy, dz) in zip(dx_list,
dy_list,
dz_list)]
if min(d_list) <= size ** 2:
return False # collision
return True # safe
def main():
print("Start " + __file__)
# init NLinkArm with Denavit-Hartenberg parameters of panda
# path_to_url
# [theta, alpha, a, d]
seven_joint_arm = RobotArm([[0., math.pi/2., 0., .333],
[0., -math.pi/2., 0., 0.],
[0., math.pi/2., 0.0825, 0.3160],
[0., -math.pi/2., -0.0825, 0.],
[0., math.pi/2., 0., 0.3840],
[0., math.pi/2., 0.088, 0.],
[0., 0., 0., 0.107]])
# ====Search Path with RRT====
obstacle_list = [
(-.3, -.3, .7, .1),
(.0, -.3, .7, .1),
(.2, -.1, .3, .15),
] # [x,y,size(radius)]
start = [0 for _ in range(len(seven_joint_arm.link_list))]
end = [1.5 for _ in range(len(seven_joint_arm.link_list))]
# Set Initial parameters
rrt_star = RRTStar(start=start,
goal=end,
rand_area=[0, 2],
max_iter=200,
robot=seven_joint_arm,
obstacle_list=obstacle_list)
path = rrt_star.planning(animation=show_animation,
search_until_max_iter=False)
if path is None:
print("Cannot find path.")
else:
print("Found path!")
# Draw final path
if show_animation:
ax = rrt_star.draw_graph()
# Plot final configuration
x_points, y_points, z_points = seven_joint_arm.get_points(path[-1])
ax.plot([x for x in x_points],
[y for y in y_points],
[z for z in z_points],
"o-", color="red", ms=5, mew=0.5)
for i, q in enumerate(path):
x_points, y_points, z_points = seven_joint_arm.get_points(q)
ax.plot([x for x in x_points],
[y for y in y_points],
[z for z in z_points],
"o-", color="grey", ms=4, mew=0.5)
plt.pause(0.1)
plt.show()
if __name__ == '__main__':
main()
``` | /content/code_sandbox/ArmNavigation/rrt_star_seven_joint_arm_control/rrt_star_seven_joint_arm_control.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 3,337 |
```python
"""
Class of n-link arm in 3D
Author: Takayuki Murooka (takayuki5168)
"""
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
class Link:
def __init__(self, dh_params):
self.dh_params_ = dh_params
def transformation_matrix(self):
theta = self.dh_params_[0]
alpha = self.dh_params_[1]
a = self.dh_params_[2]
d = self.dh_params_[3]
st = math.sin(theta)
ct = math.cos(theta)
sa = math.sin(alpha)
ca = math.cos(alpha)
trans = np.array([[ct, -st * ca, st * sa, a * ct],
[st, ct * ca, -ct * sa, a * st],
[0, sa, ca, d],
[0, 0, 0, 1]])
return trans
@staticmethod
def basic_jacobian(trans_prev, ee_pos):
pos_prev = np.array(
[trans_prev[0, 3], trans_prev[1, 3], trans_prev[2, 3]])
z_axis_prev = np.array(
[trans_prev[0, 2], trans_prev[1, 2], trans_prev[2, 2]])
basic_jacobian = np.hstack(
(np.cross(z_axis_prev, ee_pos - pos_prev), z_axis_prev))
return basic_jacobian
class NLinkArm:
def __init__(self, dh_params_list):
self.link_list = []
for i in range(len(dh_params_list)):
self.link_list.append(Link(dh_params_list[i]))
def transformation_matrix(self):
trans = np.identity(4)
for i in range(len(self.link_list)):
trans = np.dot(trans, self.link_list[i].transformation_matrix())
return trans
def forward_kinematics(self, plot=False):
trans = self.transformation_matrix()
x = trans[0, 3]
y = trans[1, 3]
z = trans[2, 3]
alpha, beta, gamma = self.euler_angle()
if plot:
self.fig = plt.figure()
self.ax = Axes3D(self.fig, auto_add_to_figure=False)
self.fig.add_axes(self.ax)
x_list = []
y_list = []
z_list = []
trans = np.identity(4)
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
for i in range(len(self.link_list)):
trans = np.dot(trans, self.link_list[i].transformation_matrix())
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4,
mew=0.5)
self.ax.plot([0], [0], [0], "o")
self.ax.set_xlim(-1, 1)
self.ax.set_ylim(-1, 1)
self.ax.set_zlim(-1, 1)
plt.show()
return [x, y, z, alpha, beta, gamma]
def basic_jacobian(self):
ee_pos = self.forward_kinematics()[0:3]
basic_jacobian_mat = []
trans = np.identity(4)
for i in range(len(self.link_list)):
basic_jacobian_mat.append(
self.link_list[i].basic_jacobian(trans, ee_pos))
trans = np.dot(trans, self.link_list[i].transformation_matrix())
return np.array(basic_jacobian_mat).T
def inverse_kinematics(self, ref_ee_pose, plot=False):
for cnt in range(500):
ee_pose = self.forward_kinematics()
diff_pose = np.array(ref_ee_pose) - ee_pose
basic_jacobian_mat = self.basic_jacobian()
alpha, beta, gamma = self.euler_angle()
K_zyz = np.array(
[[0, -math.sin(alpha), math.cos(alpha) * math.sin(beta)],
[0, math.cos(alpha), math.sin(alpha) * math.sin(beta)],
[1, 0, math.cos(beta)]])
K_alpha = np.identity(6)
K_alpha[3:, 3:] = K_zyz
theta_dot = np.dot(
np.dot(np.linalg.pinv(basic_jacobian_mat), K_alpha),
np.array(diff_pose))
self.update_joint_angles(theta_dot / 100.)
if plot:
self.fig = plt.figure()
self.ax = Axes3D(self.fig, auto_add_to_figure=False)
self.fig.add_axes(self.ax)
x_list = []
y_list = []
z_list = []
trans = np.identity(4)
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
for i in range(len(self.link_list)):
trans = np.dot(trans, self.link_list[i].transformation_matrix())
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4,
mew=0.5)
self.ax.plot([0], [0], [0], "o")
self.ax.set_xlim(-1, 1)
self.ax.set_ylim(-1, 1)
self.ax.set_zlim(-1, 1)
self.ax.plot([ref_ee_pose[0]], [ref_ee_pose[1]], [ref_ee_pose[2]],
"o")
plt.show()
def euler_angle(self):
trans = self.transformation_matrix()
alpha = math.atan2(trans[1][2], trans[0][2])
if not (-math.pi / 2 <= alpha <= math.pi / 2):
alpha = math.atan2(trans[1][2], trans[0][2]) + math.pi
if not (-math.pi / 2 <= alpha <= math.pi / 2):
alpha = math.atan2(trans[1][2], trans[0][2]) - math.pi
beta = math.atan2(
trans[0][2] * math.cos(alpha) + trans[1][2] * math.sin(alpha),
trans[2][2])
gamma = math.atan2(
-trans[0][0] * math.sin(alpha) + trans[1][0] * math.cos(alpha),
-trans[0][1] * math.sin(alpha) + trans[1][1] * math.cos(alpha))
return alpha, beta, gamma
def set_joint_angles(self, joint_angle_list):
for i in range(len(self.link_list)):
self.link_list[i].dh_params_[0] = joint_angle_list[i]
def update_joint_angles(self, diff_joint_angle_list):
for i in range(len(self.link_list)):
self.link_list[i].dh_params_[0] += diff_joint_angle_list[i]
def plot(self):
self.fig = plt.figure()
self.ax = Axes3D(self.fig)
x_list = []
y_list = []
z_list = []
trans = np.identity(4)
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
for i in range(len(self.link_list)):
trans = np.dot(trans, self.link_list[i].transformation_matrix())
x_list.append(trans[0, 3])
y_list.append(trans[1, 3])
z_list.append(trans[2, 3])
self.ax.plot(x_list, y_list, z_list, "o-", color="#00aa00", ms=4,
mew=0.5)
self.ax.plot([0], [0], [0], "o")
self.ax.set_xlabel("x")
self.ax.set_ylabel("y")
self.ax.set_zlabel("z")
self.ax.set_xlim(-1, 1)
self.ax.set_ylim(-1, 1)
self.ax.set_zlim(-1, 1)
plt.show()
``` | /content/code_sandbox/ArmNavigation/n_joint_arm_3d/NLinkArm3d.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,834 |
```python
"""
Class for controlling and plotting an arm with an arbitrary number of links.
Author: Daniel Ingram
"""
import numpy as np
import matplotlib.pyplot as plt
class NLinkArm(object):
def __init__(self, link_lengths, joint_angles, goal, show_animation):
self.show_animation = show_animation
self.n_links = len(link_lengths)
if self.n_links != len(joint_angles):
raise ValueError()
self.link_lengths = np.array(link_lengths)
self.joint_angles = np.array(joint_angles)
self.points = [[0, 0] for _ in range(self.n_links + 1)]
self.lim = sum(link_lengths)
self.goal = np.array(goal).T
if show_animation: # pragma: no cover
self.fig = plt.figure()
self.fig.canvas.mpl_connect('button_press_event', self.click)
plt.ion()
plt.show()
self.update_points()
def update_joints(self, joint_angles):
self.joint_angles = joint_angles
self.update_points()
def update_points(self):
for i in range(1, self.n_links + 1):
self.points[i][0] = self.points[i - 1][0] + \
self.link_lengths[i - 1] * \
np.cos(np.sum(self.joint_angles[:i]))
self.points[i][1] = self.points[i - 1][1] + \
self.link_lengths[i - 1] * \
np.sin(np.sum(self.joint_angles[:i]))
self.end_effector = np.array(self.points[self.n_links]).T
if self.show_animation: # pragma: no cover
self.plot()
def plot(self): # 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])
for i in range(self.n_links + 1):
if i is not self.n_links:
plt.plot([self.points[i][0], self.points[i + 1][0]],
[self.points[i][1], self.points[i + 1][1]], 'r-')
plt.plot(self.points[i][0], self.points[i][1], 'ko')
plt.plot(self.goal[0], self.goal[1], 'gx')
plt.plot([self.end_effector[0], self.goal[0]], [
self.end_effector[1], self.goal[1]], 'g--')
plt.xlim([-self.lim, self.lim])
plt.ylim([-self.lim, self.lim])
plt.draw()
plt.pause(0.0001)
def click(self, event):
self.goal = np.array([event.xdata, event.ydata]).T
self.plot()
``` | /content/code_sandbox/ArmNavigation/n_joint_arm_to_point_control/NLinkArm.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 615 |
```python
"""
Inverse kinematics for an n-link arm using the Jacobian inverse method
Author: Daniel Ingram (daniel-s-ingram)
Atsushi Sakai (@Atsushi_twi)
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent.parent))
import numpy as np
from ArmNavigation.n_joint_arm_to_point_control.NLinkArm import NLinkArm
from utils.angle import angle_mod
# Simulation parameters
Kp = 2
dt = 0.1
N_LINKS = 10
N_ITERATIONS = 10000
# States
WAIT_FOR_NEW_GOAL = 1
MOVING_TO_GOAL = 2
show_animation = True
def main(): # pragma: no cover
"""
Creates an arm using the NLinkArm class and uses its inverse kinematics
to move it to the desired position.
"""
link_lengths = [1] * N_LINKS
joint_angles = np.array([0] * N_LINKS)
goal_pos = [N_LINKS, 0]
arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation)
state = WAIT_FOR_NEW_GOAL
solution_found = False
while True:
old_goal = np.array(goal_pos)
goal_pos = np.array(arm.goal)
end_effector = arm.end_effector
errors, distance = distance_to_goal(end_effector, goal_pos)
# State machine to allow changing of goal before current goal has been reached
if state is WAIT_FOR_NEW_GOAL:
if distance > 0.1 and not solution_found:
joint_goal_angles, solution_found = inverse_kinematics(
link_lengths, joint_angles, goal_pos)
if not solution_found:
print("Solution could not be found.")
state = WAIT_FOR_NEW_GOAL
arm.goal = end_effector
elif solution_found:
state = MOVING_TO_GOAL
elif state is MOVING_TO_GOAL:
if distance > 0.1 and all(old_goal == goal_pos):
joint_angles = joint_angles + Kp * \
ang_diff(joint_goal_angles, joint_angles) * dt
else:
state = WAIT_FOR_NEW_GOAL
solution_found = False
arm.update_joints(joint_angles)
def inverse_kinematics(link_lengths, joint_angles, goal_pos):
"""
Calculates the inverse kinematics using the Jacobian inverse method.
"""
for iteration in range(N_ITERATIONS):
current_pos = forward_kinematics(link_lengths, joint_angles)
errors, distance = distance_to_goal(current_pos, goal_pos)
if distance < 0.1:
print("Solution found in %d iterations." % iteration)
return joint_angles, True
J = jacobian_inverse(link_lengths, joint_angles)
joint_angles = joint_angles + np.matmul(J, errors)
return joint_angles, False
def get_random_goal():
from random import random
SAREA = 15.0
return [SAREA * random() - SAREA / 2.0,
SAREA * random() - SAREA / 2.0]
def animation():
link_lengths = [1] * N_LINKS
joint_angles = np.array([0] * N_LINKS)
goal_pos = get_random_goal()
arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation)
state = WAIT_FOR_NEW_GOAL
solution_found = False
i_goal = 0
while True:
old_goal = np.array(goal_pos)
goal_pos = np.array(arm.goal)
end_effector = arm.end_effector
errors, distance = distance_to_goal(end_effector, goal_pos)
# State machine to allow changing of goal before current goal has been reached
if state is WAIT_FOR_NEW_GOAL:
if distance > 0.1 and not solution_found:
joint_goal_angles, solution_found = inverse_kinematics(
link_lengths, joint_angles, goal_pos)
if not solution_found:
print("Solution could not be found.")
state = WAIT_FOR_NEW_GOAL
arm.goal = get_random_goal()
elif solution_found:
state = MOVING_TO_GOAL
elif state is MOVING_TO_GOAL:
if distance > 0.1 and all(old_goal == goal_pos):
joint_angles = joint_angles + Kp * \
ang_diff(joint_goal_angles, joint_angles) * dt
else:
state = WAIT_FOR_NEW_GOAL
solution_found = False
arm.goal = get_random_goal()
i_goal += 1
if i_goal >= 5:
break
arm.update_joints(joint_angles)
def forward_kinematics(link_lengths, joint_angles):
x = y = 0
for i in range(1, N_LINKS + 1):
x += link_lengths[i - 1] * np.cos(np.sum(joint_angles[:i]))
y += link_lengths[i - 1] * np.sin(np.sum(joint_angles[:i]))
return np.array([x, y]).T
def jacobian_inverse(link_lengths, joint_angles):
J = np.zeros((2, N_LINKS))
for i in range(N_LINKS):
J[0, i] = 0
J[1, i] = 0
for j in range(i, N_LINKS):
J[0, i] -= link_lengths[j] * np.sin(np.sum(joint_angles[:j]))
J[1, i] += link_lengths[j] * np.cos(np.sum(joint_angles[:j]))
return np.linalg.pinv(J)
def distance_to_goal(current_pos, goal_pos):
x_diff = goal_pos[0] - current_pos[0]
y_diff = goal_pos[1] - current_pos[1]
return np.array([x_diff, y_diff]).T, np.hypot(x_diff, y_diff)
def ang_diff(theta1, theta2):
"""
Returns the difference between two angles in the range -pi to +pi
"""
return angle_mod(theta1 - theta2)
if __name__ == '__main__':
# main()
animation()
``` | /content/code_sandbox/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 1,334 |
```python
"""
Obstacle navigation using A* on a toroidal grid
Author: Daniel Ingram (daniel-s-ingram)
"""
from math import pi
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors
plt.ion()
# Simulation parameters
M = 100
obstacles = [[1.75, 0.75, 0.6], [0.55, 1.5, 0.5], [0, -1, 0.25]]
def main():
arm = NLinkArm([1, 1], [0, 0])
start = (10, 50)
goal = (58, 56)
grid = get_occupancy_grid(arm, obstacles)
plt.imshow(grid)
plt.show()
route = astar_torus(grid, start, goal)
for node in route:
theta1 = 2 * pi * node[0] / M - pi
theta2 = 2 * pi * node[1] / M - pi
arm.update_joints([theta1, theta2])
arm.plot(obstacles=obstacles)
def detect_collision(line_seg, circle):
"""
Determines whether a line segment (arm link) is in contact
with a circle (obstacle).
Credit to: path_to_url
Args:
line_seg: List of coordinates of line segment endpoints e.g. [[1, 1], [2, 2]]
circle: List of circle coordinates and radius e.g. [0, 0, 0.5] is a circle centered
at the origin with radius 0.5
Returns:
True if the line segment is in contact with the circle
False otherwise
"""
a_vec = np.array([line_seg[0][0], line_seg[0][1]])
b_vec = np.array([line_seg[1][0], line_seg[1][1]])
c_vec = np.array([circle[0], circle[1]])
radius = circle[2]
line_vec = b_vec - a_vec
line_mag = np.linalg.norm(line_vec)
circle_vec = c_vec - a_vec
proj = circle_vec.dot(line_vec / line_mag)
if proj <= 0:
closest_point = a_vec
elif proj >= line_mag:
closest_point = b_vec
else:
closest_point = a_vec + line_vec * proj / line_mag
if np.linalg.norm(closest_point - c_vec) > radius:
return False
return True
def get_occupancy_grid(arm, obstacles):
"""
Discretizes joint space into M values from -pi to +pi
and determines whether a given coordinate in joint space
would result in a collision between a robot arm and obstacles
in its environment.
Args:
arm: An instance of NLinkArm
obstacles: A list of obstacles, with each obstacle defined as a list
of xy coordinates and a radius.
Returns:
Occupancy grid in joint space
"""
grid = [[0 for _ in range(M)] for _ in range(M)]
theta_list = [2 * i * pi / M for i in range(-M // 2, M // 2 + 1)]
for i in range(M):
for j in range(M):
arm.update_joints([theta_list[i], theta_list[j]])
points = arm.points
collision_detected = False
for k in range(len(points) - 1):
for obstacle in obstacles:
line_seg = [points[k], points[k + 1]]
collision_detected = detect_collision(line_seg, obstacle)
if collision_detected:
break
if collision_detected:
break
grid[i][j] = int(collision_detected)
return np.array(grid)
def astar_torus(grid, start_node, goal_node):
"""
Finds a path between an initial and goal joint configuration using
the A* Algorithm on a tororiadal grid.
Args:
grid: An occupancy grid (ndarray)
start_node: Initial joint configuration (tuple)
goal_node: Goal joint configuration (tuple)
Returns:
Obstacle-free route in joint space from start_node to goal_node
"""
colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']
levels = [0, 1, 2, 3, 4, 5, 6, 7]
cmap, norm = from_levels_and_colors(levels, colors)
grid[start_node] = 4
grid[goal_node] = 5
parent_map = [[() for _ in range(M)] for _ in range(M)]
heuristic_map = calc_heuristic_map(M, goal_node)
explored_heuristic_map = np.full((M, M), np.inf)
distance_map = np.full((M, M), np.inf)
explored_heuristic_map[start_node] = heuristic_map[start_node]
distance_map[start_node] = 0
while True:
grid[start_node] = 4
grid[goal_node] = 5
current_node = np.unravel_index(
np.argmin(explored_heuristic_map, axis=None), explored_heuristic_map.shape)
min_distance = np.min(explored_heuristic_map)
if (current_node == goal_node) or np.isinf(min_distance):
break
grid[current_node] = 2
explored_heuristic_map[current_node] = np.inf
i, j = current_node[0], current_node[1]
neighbors = find_neighbors(i, j)
for neighbor in neighbors:
if grid[neighbor] == 0 or grid[neighbor] == 5:
distance_map[neighbor] = distance_map[current_node] + 1
explored_heuristic_map[neighbor] = heuristic_map[neighbor]
parent_map[neighbor[0]][neighbor[1]] = current_node
grid[neighbor] = 3
if np.isinf(explored_heuristic_map[goal_node]):
route = []
print("No route found.")
else:
route = [goal_node]
while parent_map[route[0][0]][route[0][1]] != ():
route.insert(0, parent_map[route[0][0]][route[0][1]])
print("The route found covers %d grid cells." % len(route))
for i in range(1, len(route)):
grid[route[i]] = 6
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.imshow(grid, cmap=cmap, norm=norm, interpolation=None)
plt.show()
plt.pause(1e-2)
return route
def find_neighbors(i, j):
neighbors = []
if i - 1 >= 0:
neighbors.append((i - 1, j))
else:
neighbors.append((M - 1, j))
if i + 1 < M:
neighbors.append((i + 1, j))
else:
neighbors.append((0, j))
if j - 1 >= 0:
neighbors.append((i, j - 1))
else:
neighbors.append((i, M - 1))
if j + 1 < M:
neighbors.append((i, j + 1))
else:
neighbors.append((i, 0))
return neighbors
def calc_heuristic_map(M, goal_node):
X, Y = np.meshgrid([i for i in range(M)], [i for i in range(M)])
heuristic_map = np.abs(X - goal_node[1]) + np.abs(Y - goal_node[0])
for i in range(heuristic_map.shape[0]):
for j in range(heuristic_map.shape[1]):
heuristic_map[i, j] = min(heuristic_map[i, j],
i + 1 + heuristic_map[M - 1, j],
M - i + heuristic_map[0, j],
j + 1 + heuristic_map[i, M - 1],
M - j + heuristic_map[i, 0]
)
return heuristic_map
class NLinkArm(object):
"""
Class for controlling and plotting a planar arm with an arbitrary number of links.
"""
def __init__(self, link_lengths, joint_angles):
self.n_links = len(link_lengths)
if self.n_links != len(joint_angles):
raise ValueError()
self.link_lengths = np.array(link_lengths)
self.joint_angles = np.array(joint_angles)
self.points = [[0, 0] for _ in range(self.n_links + 1)]
self.lim = sum(link_lengths)
self.update_points()
def update_joints(self, joint_angles):
self.joint_angles = joint_angles
self.update_points()
def update_points(self):
for i in range(1, self.n_links + 1):
self.points[i][0] = self.points[i - 1][0] + \
self.link_lengths[i - 1] * \
np.cos(np.sum(self.joint_angles[:i]))
self.points[i][1] = self.points[i - 1][1] + \
self.link_lengths[i - 1] * \
np.sin(np.sum(self.joint_angles[:i]))
self.end_effector = np.array(self.points[self.n_links]).T
def plot(self, obstacles=[]): # pragma: no cover
plt.cla()
for obstacle in obstacles:
circle = plt.Circle(
(obstacle[0], obstacle[1]), radius=0.5 * obstacle[2], fc='k')
plt.gca().add_patch(circle)
for i in range(self.n_links + 1):
if i is not self.n_links:
plt.plot([self.points[i][0], self.points[i + 1][0]],
[self.points[i][1], self.points[i + 1][1]], 'r-')
plt.plot(self.points[i][0], self.points[i][1], 'k.')
plt.xlim([-self.lim, self.lim])
plt.ylim([-self.lim, self.lim])
plt.draw()
plt.pause(1e-5)
if __name__ == '__main__':
main()
``` | /content/code_sandbox/ArmNavigation/arm_obstacle_navigation/arm_obstacle_navigation.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,254 |
```python
"""
Obstacle navigation using A* on a toroidal grid
Author: Daniel Ingram (daniel-s-ingram)
Tullio Facchinetti (tullio.facchinetti@unipv.it)
"""
from math import pi
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors
import sys
plt.ion()
# Simulation parameters
M = 100
obstacles = [[1.75, 0.75, 0.6], [0.55, 1.5, 0.5], [0, -1, 0.7]]
def press(event):
"""Exit from the simulation."""
if event.key == 'q' or event.key == 'Q':
print('Quitting upon request.')
sys.exit(0)
def main():
# Arm geometry in the working space
link_length = [0.5, 1.5]
initial_link_angle = [0, 0]
arm = NLinkArm(link_length, initial_link_angle)
# (x, y) co-ordinates in the joint space [cell]
start = (10, 50)
goal = (58, 56)
grid = get_occupancy_grid(arm, obstacles)
route = astar_torus(grid, start, goal)
if route:
animate(grid, arm, route)
def animate(grid, arm, route):
fig, axs = plt.subplots(1, 2)
fig.canvas.mpl_connect('key_press_event', press)
colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']
levels = [0, 1, 2, 3, 4, 5, 6, 7]
cmap, norm = from_levels_and_colors(levels, colors)
for i, node in enumerate(route):
plt.subplot(1, 2, 1)
grid[node] = 6
plt.cla()
plt.imshow(grid, cmap=cmap, norm=norm, interpolation=None)
theta1 = 2 * pi * node[0] / M - pi
theta2 = 2 * pi * node[1] / M - pi
arm.update_joints([theta1, theta2])
plt.subplot(1, 2, 2)
arm.plot_arm(plt, obstacles=obstacles)
plt.xlim(-2.0, 2.0)
plt.ylim(-3.0, 3.0)
plt.show()
# Uncomment here to save the sequence of frames
# plt.savefig('frame{:04d}.png'.format(i))
plt.pause(0.1)
def detect_collision(line_seg, circle):
"""
Determines whether a line segment (arm link) is in contact
with a circle (obstacle).
Credit to: path_to_url
Args:
line_seg: List of coordinates of line segment endpoints e.g. [[1, 1], [2, 2]]
circle: List of circle coordinates and radius e.g. [0, 0, 0.5] is a circle centered
at the origin with radius 0.5
Returns:
True if the line segment is in contact with the circle
False otherwise
"""
a_vec = np.array([line_seg[0][0], line_seg[0][1]])
b_vec = np.array([line_seg[1][0], line_seg[1][1]])
c_vec = np.array([circle[0], circle[1]])
radius = circle[2]
line_vec = b_vec - a_vec
line_mag = np.linalg.norm(line_vec)
circle_vec = c_vec - a_vec
proj = circle_vec.dot(line_vec / line_mag)
if proj <= 0:
closest_point = a_vec
elif proj >= line_mag:
closest_point = b_vec
else:
closest_point = a_vec + line_vec * proj / line_mag
if np.linalg.norm(closest_point - c_vec) > radius:
return False
return True
def get_occupancy_grid(arm, obstacles):
"""
Discretizes joint space into M values from -pi to +pi
and determines whether a given coordinate in joint space
would result in a collision between a robot arm and obstacles
in its environment.
Args:
arm: An instance of NLinkArm
obstacles: A list of obstacles, with each obstacle defined as a list
of xy coordinates and a radius.
Returns:
Occupancy grid in joint space
"""
grid = [[0 for _ in range(M)] for _ in range(M)]
theta_list = [2 * i * pi / M for i in range(-M // 2, M // 2 + 1)]
for i in range(M):
for j in range(M):
arm.update_joints([theta_list[i], theta_list[j]])
points = arm.points
collision_detected = False
for k in range(len(points) - 1):
for obstacle in obstacles:
line_seg = [points[k], points[k + 1]]
collision_detected = detect_collision(line_seg, obstacle)
if collision_detected:
break
if collision_detected:
break
grid[i][j] = int(collision_detected)
return np.array(grid)
def astar_torus(grid, start_node, goal_node):
"""
Finds a path between an initial and goal joint configuration using
the A* Algorithm on a tororiadal grid.
Args:
grid: An occupancy grid (ndarray)
start_node: Initial joint configuration (tuple)
goal_node: Goal joint configuration (tuple)
Returns:
Obstacle-free route in joint space from start_node to goal_node
"""
colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']
levels = [0, 1, 2, 3, 4, 5, 6, 7]
cmap, norm = from_levels_and_colors(levels, colors)
grid[start_node] = 4
grid[goal_node] = 5
parent_map = [[() for _ in range(M)] for _ in range(M)]
heuristic_map = calc_heuristic_map(M, goal_node)
explored_heuristic_map = np.full((M, M), np.inf)
distance_map = np.full((M, M), np.inf)
explored_heuristic_map[start_node] = heuristic_map[start_node]
distance_map[start_node] = 0
while True:
grid[start_node] = 4
grid[goal_node] = 5
current_node = np.unravel_index(
np.argmin(explored_heuristic_map, axis=None), explored_heuristic_map.shape)
min_distance = np.min(explored_heuristic_map)
if (current_node == goal_node) or np.isinf(min_distance):
break
grid[current_node] = 2
explored_heuristic_map[current_node] = np.inf
i, j = current_node[0], current_node[1]
neighbors = find_neighbors(i, j)
for neighbor in neighbors:
if grid[neighbor] == 0 or grid[neighbor] == 5:
distance_map[neighbor] = distance_map[current_node] + 1
explored_heuristic_map[neighbor] = heuristic_map[neighbor]
parent_map[neighbor[0]][neighbor[1]] = current_node
grid[neighbor] = 3
if np.isinf(explored_heuristic_map[goal_node]):
route = []
print("No route found.")
else:
route = [goal_node]
while parent_map[route[0][0]][route[0][1]] != ():
route.insert(0, parent_map[route[0][0]][route[0][1]])
print("The route found covers %d grid cells." % len(route))
for i in range(1, len(route)):
grid[route[i]] = 6
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.imshow(grid, cmap=cmap, norm=norm, interpolation=None)
plt.show()
plt.pause(1e-2)
return route
def find_neighbors(i, j):
neighbors = []
if i - 1 >= 0:
neighbors.append((i - 1, j))
else:
neighbors.append((M - 1, j))
if i + 1 < M:
neighbors.append((i + 1, j))
else:
neighbors.append((0, j))
if j - 1 >= 0:
neighbors.append((i, j - 1))
else:
neighbors.append((i, M - 1))
if j + 1 < M:
neighbors.append((i, j + 1))
else:
neighbors.append((i, 0))
return neighbors
def calc_heuristic_map(M, goal_node):
X, Y = np.meshgrid([i for i in range(M)], [i for i in range(M)])
heuristic_map = np.abs(X - goal_node[1]) + np.abs(Y - goal_node[0])
for i in range(heuristic_map.shape[0]):
for j in range(heuristic_map.shape[1]):
heuristic_map[i, j] = min(heuristic_map[i, j],
i + 1 + heuristic_map[M - 1, j],
M - i + heuristic_map[0, j],
j + 1 + heuristic_map[i, M - 1],
M - j + heuristic_map[i, 0]
)
return heuristic_map
class NLinkArm(object):
"""
Class for controlling and plotting a planar arm with an arbitrary number of links.
"""
def __init__(self, link_lengths, joint_angles):
self.n_links = len(link_lengths)
if self.n_links != len(joint_angles):
raise ValueError()
self.link_lengths = np.array(link_lengths)
self.joint_angles = np.array(joint_angles)
self.points = [[0, 0] for _ in range(self.n_links + 1)]
self.lim = sum(link_lengths)
self.update_points()
def update_joints(self, joint_angles):
self.joint_angles = joint_angles
self.update_points()
def update_points(self):
for i in range(1, self.n_links + 1):
self.points[i][0] = self.points[i - 1][0] + \
self.link_lengths[i - 1] * \
np.cos(np.sum(self.joint_angles[:i]))
self.points[i][1] = self.points[i - 1][1] + \
self.link_lengths[i - 1] * \
np.sin(np.sum(self.joint_angles[:i]))
self.end_effector = np.array(self.points[self.n_links]).T
def plot_arm(self, myplt, obstacles=[]): # pragma: no cover
myplt.cla()
for obstacle in obstacles:
circle = myplt.Circle(
(obstacle[0], obstacle[1]), radius=0.5 * obstacle[2], fc='k')
myplt.gca().add_patch(circle)
for i in range(self.n_links + 1):
if i is not self.n_links:
myplt.plot([self.points[i][0], self.points[i + 1][0]],
[self.points[i][1], self.points[i + 1][1]], 'r-')
myplt.plot(self.points[i][0], self.points[i][1], 'k.')
myplt.xlim([-self.lim, self.lim])
myplt.ylim([-self.lim, self.lim])
myplt.draw()
# myplt.pause(1e-5)
if __name__ == '__main__':
main()
``` | /content/code_sandbox/ArmNavigation/arm_obstacle_navigation/arm_obstacle_navigation_2.py | python | 2016-03-21T09:34:43 | 2024-08-16T19:00:08 | PythonRobotics | AtsushiSakai/PythonRobotics | 22,516 | 2,601 |
```php
<?php namespace Tests\Concerns;
use App\Models\Account;
use App\Models\AccountPaymentGateway;
use App\Models\Attendee;
use App\Models\Country;
use App\Models\Currency;
use App\Models\Event;
use App\Models\EventStats;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderStatus;
use App\Models\Organiser;
use App\Models\PaymentGateway;
use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\Timezone;
use App\Models\User;
use Illuminate\Support\Carbon;
use Superbalist\Money\Money;
trait OrganisationWithTax
{
private $account;
private $currency;
private $paymentGateway;
private $user;
private $organiserWithTax;
private $event;
private $eventWithPercentageFees;
private $eventWithFixedFees;
public function setupOrganisationWithTax()
{
$orderStatuses = collect([
['id' => config('attendize.order.complete'), 'name' => 'Completed'],
['id' => config('attendize.order.refunded'), 'name' => 'Refunded'],
['id' => config('attendize.order.partially_refunded'), 'name' => 'Partially Refunded'],
['id' => config('attendize.order.cancelled'), 'name' => 'Cancelled'],
]);
$orderStatuses->map(static function ($orderStatus) {
factory(OrderStatus::class)->create($orderStatus);
});
$ticketStatuses = collect([
['name' => 'Sold Out'],
['name' => 'Sales Have Ended'],
['name' => 'Not On Sale Yet'],
['name' => 'On Sale'],
]);
$ticketStatuses->map(function ($ticketStatus) {
factory(TicketStatus::class)->create($ticketStatus);
});
$country = factory(Country::class)->states('United Kingdom')->create();
$currency = factory(Currency::class)->states('GBP')->create();
$timezone = factory(Timezone::class)->states('Europe/London')->create();
$this->paymentGateway = factory(PaymentGateway::class)->states('Dummy')->create();
// Setup base account information with correct country, currency and timezones
$this->account = factory(Account::class)->create([
'name' => 'Local Integration Test Account',
'timezone_id' => $timezone->id, // London
'currency_id' => $currency->id, // Pound
'country_id' => $country->id, // UK
'payment_gateway_id' => $this->paymentGateway->id, // Dummy
]);
factory(AccountPaymentGateway::class)->create([
'account_id' => $this->account->id,
'payment_gateway_id' => $this->paymentGateway->id,
]);
$this->user = factory(User::class)->create([
'account_id' => $this->account->id,
'email' => 'local@test.com',
'password' => \Hash::make('pass'),
'is_parent' => true, // Top level user
'is_registered' => true,
'is_confirmed' => true,
]);
$this->organiserWithTax = factory(Organiser::class)->create([
'account_id' => $this->account->id,
'name' => 'Test Organiser (With Tax)',
'charge_tax' => true,
'tax_name' => 'VAT',
'tax_value' => 20.00
]);
$this->event = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $this->organiserWithTax->id,
'title' => 'Event without Fees',
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
$this->eventWithPercentageFees = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $this->organiserWithTax->id,
'title' => 'Event with Percentage Fees And Tax',
'organiser_fee_fixed' => 0.00,
'organiser_fee_percentage' => 12.0,
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
$this->eventWithFixedFees = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $this->organiserWithTax->id,
'title' => 'Event with Fixed Fees',
'organiser_fee_fixed' => 3.50,
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
}
public function makeTicketOrder($count = 1, $price = 150.00, $hasPercentageFee = false, $hasFixedFee = false)
{
$salesVolume = (new Money($price))->multiply($count);
// Every organization can have events with or without fees
$eventId = $this->event->id;
$organiserFees = new Money('0');
if ($hasPercentageFee) {
$eventId = $this->eventWithPercentageFees->id;
$organiserFeePercentage = (new Money($this->eventWithPercentageFees->organiser_fee_percentage))->divide(100);
$organiserFees = (new Money($price))->multiply($organiserFeePercentage);
} else {
if ($hasFixedFee) {
$eventId = $this->eventWithFixedFees->id;
$organiserFees = new Money($this->eventWithFixedFees->organiser_fee_fixed);
}
}
$organiserFeesVolume = $organiserFees->multiply($count);
// Work out the tax amount from the ticket prices and booking fees
$organiserTaxRate = (new Money($this->organiserWithTax->tax_value))->divide(100);
$subTotal = $salesVolume->add($organiserFeesVolume);
$taxAmount = $subTotal->multiply($organiserTaxRate);
$ticket = factory(Ticket::class)->create([
'user_id' => $this->user->id,
'edited_by_user_id' => $this->user->id,
'account_id' => $this->account->id,
'order_id' => null,
'event_id' => $eventId,
'title' => 'Ticket',
'price' => $price,
'is_hidden' => false,
'quantity_sold' => $count,
'sales_volume' => $salesVolume->toFloat(),
'organiser_fees_volume' => $organiserFeesVolume->toFloat(),
]);
$singleAttendeeOrder = factory(Order::class)->create([
'account_id' => $this->account->id,
'payment_gateway_id' => $this->paymentGateway->id,
'order_status_id' => OrderStatus::where('name', 'Completed')->first(), // Completed Order
'discount' => 0.00,
'booking_fee' => 0.00,
'organiser_booking_fee' => $organiserFeesVolume->toFloat(),
'amount' => $salesVolume->toFloat(),
'event_id' => $eventId,
'is_payment_received' => true,
'taxamt' => $taxAmount,
]);
$singleAttendeeOrder->tickets()->attach($ticket);
factory(OrderItem::class)->create([
'title' => $ticket->title,
'quantity' => $count,
'unit_price' => $price,
'unit_booking_fee' => $organiserFees->toFloat(),
'order_id' => $singleAttendeeOrder->id,
]);
// Add the number of attendees based on the count
$attendees = factory(Attendee::class, $count)->create([
'order_id' => $singleAttendeeOrder->id,
'event_id' => $eventId,
'ticket_id' => $ticket->id,
'account_id' => $this->account->id,
]);
factory(EventStats::class)->create([
'date' => Carbon::now()->format('Y-m-d'),
'views' => 0,
'unique_views' => 0,
'tickets_sold' => $count,
'sales_volume' => $salesVolume->toFloat(),
'event_id' => $eventId,
'organiser_fees_volume' => $organiserFeesVolume->toFloat(),
]);
return [$singleAttendeeOrder, $attendees];
}
public function getAccountUser()
{
return $this->user;
}
}
``` | /content/code_sandbox/tests/Concerns/OrganisationWithTax.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,009 |
```php
<?php
return [
// The default gateway to use
'default' => 'stripe',
// Add in each gateway here
'gateways' => [
'paypal' => [
'driver' => 'PayPal_Express',
'options' => [
'solutionType' => '',
'landingPage' => '',
'headerImageUrl' => '',
],
],
'stripe' => [
'driver' => 'Stripe',
'options' => [],
],
],
];
``` | /content/code_sandbox/config/laravel-omnipay.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 114 |
```php
<?php namespace Tests\Concerns;
use App\Models\Event;
use App\Models\Account;
use App\Models\AccountPaymentGateway;
use App\Models\Attendee;
use App\Models\Country;
use App\Models\Currency;
use App\Models\EventStats;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderStatus;
use App\Models\Organiser;
use App\Models\PaymentGateway;
use App\Models\Ticket;
use App\Models\TicketStatus;
use App\Models\Timezone;
use App\Models\User;
use Superbalist\Money\Money;
use Illuminate\Support\Carbon;
trait OrganisationWithoutTax
{
private $account;
private $paymentGateway;
private $user;
private $event;
private $eventWithPercentageFees;
private $eventWithFixedFees;
public function setupOrganisationWithoutTax()
{
$orderStatuses = collect([
['id' => config('attendize.order.complete'), 'name' => 'Completed'],
['id' => config('attendize.order.refunded'), 'name' => 'Refunded'],
['id' => config('attendize.order.partially_refunded'), 'name' => 'Partially Refunded'],
['id' => config('attendize.order.cancelled'), 'name' => 'Cancelled'],
]);
$orderStatuses->map(function($orderStatus) {
factory(OrderStatus::class)->create($orderStatus);
});
$ticketStatuses = collect([
['name' => 'Sold Out'],
['name' => 'Sales Have Ended'],
['name' => 'Not On Sale Yet'],
['name' => 'On Sale'],
]);
$ticketStatuses->map(function($ticketStatus) {
factory(TicketStatus::class)->create($ticketStatus);
});
$country = factory(Country::class)->states('United Kingdom')->create();
$currency = factory(Currency::class)->states('GBP')->create();
$timezone = factory(Timezone::class)->states('Europe/London')->create();
$this->paymentGateway = factory(PaymentGateway::class)->states('Dummy')->create();
// Setup base account information with correct country, currency and timezones
$this->account = factory(Account::class)->create([
'name' => 'Local Integration Test Account',
'timezone_id' => $timezone->id, // London
'currency_id' => $currency->id, // Pound
'country_id' => $country->id, // UK
'payment_gateway_id' => $this->paymentGateway->id, // Dummy
]);
factory(AccountPaymentGateway::class)->create([
'account_id' => $this->account->id,
'payment_gateway_id' => $this->paymentGateway->id,
]);
$this->user = factory(User::class)->create([
'account_id' => $this->account->id,
'email' => 'local@test.com',
'password' => \Hash::make('pass'),
'is_parent' => true, // Top level user
'is_registered' => true,
'is_confirmed' => true,
]);
$organiserNoTax = factory(Organiser::class)->create([
'account_id' => $this->account->id,
'name' => 'Test Organiser (No Tax)',
'charge_tax' => false,
'tax_name' => '',
'tax_value' => 0.00
]);
$this->event = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $organiserNoTax->id,
'title' => 'Event without Fees',
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
$this->eventWithPercentageFees = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $organiserNoTax->id,
'title' => 'Event with Percentage Fees',
'organiser_fee_percentage' => 5.0,
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
$this->eventWithFixedFees = factory(Event::class)->create([
'account_id' => $this->account->id,
'user_id' => $this->user->id,
'organiser_id' => $organiserNoTax->id,
'title' => 'Event with Fixed Fees',
'organiser_fee_fixed' => 2.50,
'currency_id' => $currency->id, // Pound
'is_live' => true,
]);
}
public function makeTicketOrder($count = 1, $price = 100.00, $hasPercentageFee = false, $hasFixedFee = false)
{
$salesVolume = (new Money($price))->multiply($count)->toFloat();
// Every organisation can have events with or without fees
$eventId = $this->event->id;
$organiserFees = new Money('0');
if ($hasPercentageFee) {
$eventId = $this->eventWithPercentageFees->id;
$organiserFeePercentage = (new Money($this->eventWithPercentageFees->organiser_fee_percentage))->divide(100);
$organiserFees = (new Money($price))->multiply($organiserFeePercentage);
} else if ($hasFixedFee) {
$eventId = $this->eventWithFixedFees->id;
$organiserFees = new Money($this->eventWithFixedFees->organiser_fee_fixed);
}
$ticket = factory(Ticket::class)->create([
'user_id' => $this->user->id,
'edited_by_user_id' => $this->user->id,
'account_id' => $this->account->id,
'order_id' => null,
'event_id' => $eventId,
'title' => 'Ticket',
'price' => $price,
'is_hidden' => false,
'quantity_sold' => $count,
'sales_volume' => $salesVolume,
'organiser_fees_volume' => $organiserFees->multiply($count)->toFloat(),
]);
$singleAttendeeOrder = factory(Order::class)->create([
'account_id' => $this->account->id,
'payment_gateway_id' => $this->paymentGateway->id,
'order_status_id' => OrderStatus::where('name', 'Completed')->first(), // Completed Order
'discount' => 0.00,
'booking_fee' => 0.00,
'organiser_booking_fee' => $organiserFees->multiply($count)->toFloat(),
'amount' => $salesVolume,
'event_id' => $eventId,
'is_payment_received' => true,
]);
$singleAttendeeOrder->tickets()->attach($ticket);
factory(OrderItem::class)->create([
'title' => $ticket->title,
'quantity' => $count,
'unit_price' => $price,
'unit_booking_fee' => $organiserFees->toFloat(),
'order_id' => $singleAttendeeOrder->id,
]);
// Add the number of attendees based on the count
$attendees = factory(Attendee::class, $count)->create([
'order_id' => $singleAttendeeOrder->id,
'event_id' => $eventId,
'ticket_id' => $ticket->id,
'account_id' => $this->account->id,
]);
factory(EventStats::class)->create([
'date' => Carbon::now()->format('Y-m-d'),
'views' => 0,
'unique_views' => 0,
'tickets_sold' => $count,
'sales_volume' => $salesVolume,
'event_id' => $eventId,
'organiser_fees_volume' => $organiserFees->multiply($count)->toFloat(),
]);
return [ $singleAttendeeOrder, $attendees ];
}
public function getAccountUser()
{
return $this->user;
}
}
``` | /content/code_sandbox/tests/Concerns/OrganisationWithoutTax.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,807 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Event;
class EventAttendeesTest extends TestCase
{
public function test_event_attendees_are_displayed()
{
// Create organiser with account id = 1 to skip first run
$organiser = factory(App\Models\Organiser::class)->create([
'account_id' => 1
]);
$event = factory(App\Models\Event::class)->create([
'account_id' => $organiser->account_id,
]);
$attendee = factory(App\Models\Attendee::class)->create([
'account_id' => $organiser->account_id,
'event_id' => $event->id,
'first_name' => 'Test First Name',
'last_name' => 'Test Last Name',
]);
$this->actingAs($this->test_user)
->visit(route('showEventAttendees', ['event_id' => $attendee->event->id]))
->see('Attendees')
->see('Test First Name')
->see('Test Last Name');
}
}
``` | /content/code_sandbox/tests/deprecated/EventAttendeesTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 254 |
```php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Tests\Concerns\DatabaseSetup;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, DatabaseSetup;
/**
* Initializes the tests
*/
public function setUp(): void
{
parent::setUp();
$this->setupDatabase();
}
/**
* Checks if there are multiple records in the database.
*
* You must pass an associative array with the name of the table
* as key and an array with the name of the column and the value.
*
* For example:
*
* [
* 'table_1' => [
* 'column_1' => 'value to check',
* 'column_2' => 'value to check',
* 'column_3' => 'value to check'
* ],
* 'table_2' => [
* 'column_1' => 'value to check',
* 'column_2' => 'value to check',
* 'column_3' => 'value to check'
* ]
* ]
*
* @param array $expected Array with tables/columns to check
*/
public function assertDatabaseHasMany(array $expected = []): void
{
collect($expected)->each(function ($data, $table) {
$this->assertDatabaseHas($table, $data);
});
}
}
``` | /content/code_sandbox/tests/TestCase.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 320 |
```php
<?php namespace Tests\Features;
use App\Models\Attendee;
use Tests\Concerns\OrganisationWithTax;
use Tests\TestCase;
class OrganisationWithTaxTest extends TestCase
{
use OrganisationWithTax;
public function setUp(): void
{
parent::setUp();
$this->withoutMiddleware([
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\FirstRunMiddleware::class,
]);
$this->setupOrganisationWithTax();
}
/**
* @test
*/
public function cancels_and_refunds_order_with_single_ticket_and_tax()
{
// Setup single attendee order
[$order, $attendees] = $this->makeTicketOrder(1, 150.00);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 0.00,
'amount' => 150.00,
'amount_refunded' => 180.00,
'taxamt' => 30.00,
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function cancels_and_refunds_order_with_multiple_tickets_and_tax()
{
// Setup multiple attendee order but refund only 3 out of 5
[$order, $attendees] = $this->makeTicketOrder(5, 150.00);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
$attendeeIds[2],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 2,
'sales_volume' => 300.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 300.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 2,
],
'orders' => [
'organiser_booking_fee' => 0.00,
'amount' => 750.00,
'amount_refunded' => 540.00,
'taxamt' => 150.00,
'is_partially_refunded' => true,
],
]);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
/**
* @test
*/
public function your_sha256_hashtage_booking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(1, 150.00, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 18.00, // 12% fee
'amount' => 150.00,
'amount_refunded' => 201.60,
'taxamt' => 33.6, // 20% VAT
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function your_sha256_hashcentage_booking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(5, 120.00, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
$attendeeIds[2],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$eventStats = \App\Models\EventStats::first()
->only('tickets_sold', 'sales_volume', 'organiser_fees_volume');
$this->assertEquals([
'tickets_sold' => 2,
'sales_volume' => 240,
'organiser_fees_volume' => 28.8, // 12% Fees
], $eventStats);
$tickets = \App\Models\Ticket::first()
->only('sales_volume', 'organiser_fees_volume', 'quantity_sold');
$this->assertEquals([
'quantity_sold' => 2,
'sales_volume' => 240,
'organiser_fees_volume' => 28.8, // 12% Fees
], $tickets);
$order = \App\Models\Order::first()
->only('organiser_booking_fee', 'amount', 'amount_refunded', 'taxamt', 'is_partially_refunded');
$this->assertEquals([
'organiser_booking_fee' => 72.00, // 12% Fees
'amount' => 600.00,
'amount_refunded' => 483.84,
'taxamt' => 134.40, // 20% VAT
'is_partially_refunded' => true,
], $order);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
/**
* @test
*/
public function your_sha256_hashbooking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(1, 50.00, false, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 3.50, // Fixed fee
'amount' => 50.00,
'amount_refunded' => 64.20,
'taxamt' => 10.70, // 20% VAT
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function your_sha256_hashed_booking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(5, 240.00, false, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 3,
'sales_volume' => 720.00,
'organiser_fees_volume' => 10.50, // Fixed fee 3.50
],
'tickets' => [
'sales_volume' => 720.00,
'organiser_fees_volume' => 10.50,
'quantity_sold' => 3,
],
'orders' => [
'organiser_booking_fee' => 17.50, // Fixed fee 3.50
'amount' => 1200.00,
'amount_refunded' => 584.40,
'taxamt' => 243.50, // 20% VAT
'is_partially_refunded' => true,
],
]);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
$this->assertFalse(Attendee::find($attendeeIds[2])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[2])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
}
``` | /content/code_sandbox/tests/Feature/OrderCancellation/OrganisationWithTaxTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,698 |
```yaml
version: '3.2'
services:
web:
image: attendize_web:latest
ports:
- "8080:80"
- "8081:443"
volumes:
- .:/usr/share/nginx/html
- .:/var/www
depends_on:
- db
- maildev
- redis
- worker
env_file:
- ./.env
worker:
image: attendize_worker:latest
depends_on:
- db
- maildev
- redis
volumes:
- .:/usr/share/nginx/html
- .:/var/www
db:
image: mysql:5.7.23
restart: always
env_file:
- ./.env
environment:
MYSQL_ROOT_PASSWORD: "yes"
MYSQL_HOST: ${DB_HOST}
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_USER: ${DB_USERNAME}
MYSQL_PASSWORD: ${DB_PASSWORD}
ports:
- "3306:3306"
volumes:
- "mysql-data:/var/lib/mysql"
maildev:
image: maildev/maildev
ports:
- "1080:1080"
redis:
image: redis
volumes:
mysql-data:
``` | /content/code_sandbox/docker-compose.yml | yaml | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 275 |
```javascript
module.exports = function (grunt) {
//Initializing the configuration object
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration
less: {
development: {
options: {
compress: true,
javascriptEnabled: true,
},
files: {
"./public/assets/stylesheet/application.css": "./public/assets/stylesheet/application.less",
"./public/assets/stylesheet/frontend.css": "./public/assets/stylesheet/frontend.less",
}
},
},
concat: {
options: {
separator: ';',
stripBanners: {
block: true,
line: true
},
},
js_frontend: {
src: [
'./public/vendor/jquery/dist/jquery.min.js',
'./public/vendor/bootstrap/dist/js/bootstrap.js',
'./public/vendor/jquery-form/jquery.form.js',
'./public/vendor/RRSSB/js/rrssb.js',
'./public/vendor/humane-js/humane.js',
'./public/vendor/jquery.payment/lib/jquery.payment.js',
'./public/assets/javascript/app-public.js'
],
dest: './public/assets/javascript/frontend.js',
},
js_backend: {
src: [
'./public/vendor/modernizr/modernizr.js',
'./public/vendor/html.sortable/dist/html.sortable.js',
'./public/vendor/bootstrap/dist/js/bootstrap.js',
'./public/vendor/jquery-form/jquery.form.js',
'./public/vendor/humane-js/humane.js',
'./public/vendor/RRSSB/js/rrssb.js',
'./public/vendor/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.js',
'./public/vendor/datetimepicker/dist/DateTimePicker.js',
'./public/vendor/jquery-minicolors/jquery.minicolors.min.js',
'./public/assets/javascript/app.js'
],
dest: './public/assets/javascript/backend.js',
},
},
uglify: {
options: {
mangle: true, // Use if you want the names of your functions and variables unchanged
preserveComments: false,
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */',
},
frontend: {
files: {
'./public/assets/javascript/frontend.js': ['<%= concat.js_frontend.dest %>'],
}
},
backend: {
files: {
'./public/assets/javascript/backend.js': './public/assets/javascript/backend.js',
}
},
},
watch: {
scripts: {
files: ['./public/assets/**/*.js'],
tasks: ['default'],
options: {
spawn: false,
},
},
}
});
// Plugin loading
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
// Task definition
grunt.registerTask('default', ['less', 'concat']);
grunt.registerTask('deploy', ['less', 'concat', 'uglify']);
grunt.registerTask('js', ['concat']);
grunt.registerTask('styles', ['concat']);
grunt.registerTask('minify', ['uglify']);
};
``` | /content/code_sandbox/Gruntfile.js | javascript | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 673 |
```yaml
suites:
main:
namespace: App
psr4_prefix: App
src_path: app
``` | /content/code_sandbox/phpspec.yml | yaml | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 25 |
```php
<?php namespace Tests\Features;
use App\Attendize\Utils;
use Tests\TestCase;
class UtilsTest extends TestCase
{
/**
* @test
*/
public function parse_version_correctly()
{
$parsed_version = Utils::parse_version("1.1.0");
$this->assertEquals($parsed_version, "1.1.0");
$parsed_version = Utils::parse_version("Version 1.1.0 RC");
$this->assertEquals($parsed_version, "1.1.0");
$parsed_version = Utils::parse_version("<script>alert(1)</script>");
$this->assertEquals($parsed_version, "");
}
}
``` | /content/code_sandbox/tests/Feature/Utils/UtilsTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 143 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Attendize\Utils;
class UserTest extends TestCase
{
public function test_edit_user_is_successful()
{
$this->actingAs($this->test_user);
factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$firstName = $this->faker->firstName;
$lastName = $this->faker->lastName;
$email = 'new@email.com.au';
$post = array(
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
);
$this->call('post', route('postEditUser'), $post, $server);
$this->seeJson([
'status' => 'success',
'message' => 'Successfully Saved Details',
]);
$user = App\Models\User::find($this->test_user->id);
$this->assertEquals($firstName, $user->first_name);
$this->assertEquals($lastName, $user->last_name);
$this->assertEquals($email, $user->email);
}
public function test_edit_user_is_successful_when_changing_password()
{
$this->actingAs($this->test_user);
$previousPassword = $this->test_user->password;
factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$firstName = $this->faker->firstName;
$lastName = $this->faker->lastName;
$email = 'new@email.com.au';
$post = array(
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'password' => $this->test_user_password,
'new_password' => 'newpassword',
'new_password_confirmation' => 'newpassword',
);
$this->call('post', route('postEditUser'), $post, $server);
$this->seeJson([
'status' => 'success',
'message' => 'Successfully Saved Details',
]);
$user = App\Models\User::find($this->test_user->id);
$this->assertEquals($firstName, $user->first_name);
$this->assertEquals($lastName, $user->last_name);
$this->assertEquals($email, $user->email);
$this->assertNotEquals($previousPassword, $user->password);
}
public function test_edit_user_is_unsuccessful_because_of_invalid_email()
{
$this->actingAs($this->test_user);
factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$firstName = $this->faker->firstName;
$lastName = $this->faker->lastName;
$email = 'new@email';
$post = array(
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
);
$this->call('post', route('postEditUser'), $post, $server);
$this->seeJson([
'status' => 'error',
]);
}
public function test_edit_user_is_unsuccessful_because_of_no_first_name()
{
$this->actingAs($this->test_user);
factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$lastName = $this->faker->lastName;
$email = 'new@email';
$post = array(
'first_name' => '',
'last_name' => $lastName,
'email' => $email,
);
$this->call('post', route('postEditUser'), $post, $server);
$this->seeJson([
'status' => 'error',
]);
}
public function test_edit_user_is_unsuccessful_because_of_no_last_name()
{
$this->actingAs($this->test_user);
factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$firstName = $this->faker->firstName;
$email = 'new@email';
$post = array(
'first_name' => $firstName,
'last_name' => '',
'email' => $email,
);
$this->call('post', route('postEditUser'), $post, $server);
$this->seeJson([
'status' => 'error',
]);
}
}
``` | /content/code_sandbox/tests/deprecated/UserTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,051 |
```php
<?php
/*
|your_sha256_hash----------
| Create The Application
|your_sha256_hash----------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|your_sha256_hash----------
| Bind Important Interfaces
|your_sha256_hash----------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|your_sha256_hash----------
| Return The Application
|your_sha256_hash----------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
``` | /content/code_sandbox/bootstrap/app.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 292 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Organiser;
class OrganiserTest extends TestCase
{
/**
* @group passing
*/
public function test_create_organiser_is_successful_when_charge_tax_is_no()
{
$email = $this->faker->email;
$this->actingAs($this->test_user)
->visit(route('showCreateOrganiser'))
->type($this->faker->name, 'name')
->type($email, 'email')
->type('No', 'charge_tax')
->press('Create Organiser')
->seeJson([
'status' => 'success'
]);
//get the most recently created organiser from database
$this->organiser = Organiser::where('email','=', $email)->orderBy('created_at', 'desc')->first();
//check the charge tax flag is 0
$this->assertEquals($this->organiser->charge_tax, 0);
}
/**
* @group passing
*/
public function test_create_organiser_is_successful_when_charge_tax_is_yes()
{
$email = $this->faker->email;
$this->actingAs($this->test_user)
->visit(route('showCreateOrganiser'))
->type($this->faker->name, 'name')
->type($email, 'email')
->type('organisers', 'tax_name')
->type(12323, 'tax_id')
->type(15, 'tax_value')
->type('Yes', 'charge_tax')
->press('Create Organiser')
->seeJson([
'status' => 'success'
]);
//get the most recently created organiser from database
$this->organiser = Organiser::where('email','=', $email)->orderBy('created_at', 'desc')->first();
//check the charge tax flag is 1
$this->assertEquals($this->organiser->charge_tax, 1);
}
/**
* @group passing
*/
public function test_create_organiser_fails_when_organiser_details_missing()
{
$this->actingAs($this->test_user)
->visit(route('showCreateOrganiser'))
->type('', 'name')
->type('', 'email')
->type('No', 'charge_tax')
->press('Create Organiser')
->seeJson([
'status' => 'error'
]);
}
}
``` | /content/code_sandbox/tests/deprecated/OrganiserTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 548 |
```php
<?php
return [
/*
|your_sha256_hash----------
| Application Name
|your_sha256_hash----------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|your_sha256_hash----------
| Application Environment
|your_sha256_hash----------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|your_sha256_hash----------
| Application Debug Mode
|your_sha256_hash----------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
/*
|your_sha256_hash----------
| Application URL
|your_sha256_hash----------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'path_to_url
'asset_url' => env('ASSET_URL', null),
/*
|your_sha256_hash----------
| Application Timezone
|your_sha256_hash----------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => env('TIMEZONE', 'UTC'),
/*
|your_sha256_hash----------
| Application Locale Configuration
|your_sha256_hash----------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|your_sha256_hash----------
| Application Locale Direction Configuration
|your_sha256_hash----------
|
| The application locale direction checks if dir is ltr or rtl.
|
*/
'locale_dir' => 'ltr',
/*
|your_sha256_hash----------
| Application Fallback Locale
|your_sha256_hash----------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|your_sha256_hash----------
| Faker Locale
|your_sha256_hash----------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|your_sha256_hash----------
| Encryption Key
|your_sha256_hash----------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|your_sha256_hash----------
| Autoloaded Service Providers
|your_sha256_hash----------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Maatwebsite\Excel\ExcelServiceProvider::class,
/*
* Attendize Service Providers
*/
App\Providers\BladeServiceProvider::class,
App\Providers\HtmlMacroServiceProvider::class,
App\Providers\HelpersServiceProvider::class,
Nitmedia\Wkhtml2pdf\L5Wkhtml2pdfServiceProvider::class,
],
/*
|your_sha256_hash----------
| Class Aliases
|your_sha256_hash----------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
// Attendize Class Alias
'Markdown' => GrahamCampbell\Markdown\Facades\Markdown::class,
'PDF' => Nitmedia\Wkhtml2pdf\Facades\Wkhtml2pdf::class,
'Utils' => App\Attendize\Utils::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
];
``` | /content/code_sandbox/config/app.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,912 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Organiser;
class OrganiserEventsTest extends TestCase
{
public function test_show_events_displays_events()
{
$organiser = factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$event1 = factory(App\Models\Event::class)->create([
'account_id' => $organiser->account_id,
'organiser_id' => $organiser->id,
'user_id' => $this->test_user->id,
]);
$event2 = factory(App\Models\Event::class)->create([
'account_id' => $organiser->account_id,
'organiser_id' => $organiser->id,
'user_id' => $this->test_user->id,
]);
$this->actingAs($this->test_user)
->visit(route('showOrganiserEvents', ['organiser_id' => $organiser->id]))
->see($event1->title)
->see($event2->title)
->see('2 events');
}
}
``` | /content/code_sandbox/tests/deprecated/OrganiserEventsTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 259 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Event;
class EventTest extends TestCase
{
public function test_event_is_created_successfully()
{
$this->actingAs($this->test_user);
$organiser = factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$post = array(
'organiser_id' => $organiser->id,
'title' => $this->faker->text,
'description' => $this->faker->paragraph,
'location_venue_name' => $this->faker->company,
'location_address_line_1' => $this->faker->streetAddress,
'location_address_line_2' => '',
'location_state' => $this->faker->city,
'location_post_code' => $this->faker->postcode,
'start_date' => date('d-m-Y H:i', strtotime('+ 30 days')),
'end_date' => date('d-m-Y H:i', strtotime('+ 60 days')),
);
$this->call('post', route('postCreateEvent'), $post, $server);
$this->seeJson([
'status' => 'success',
'id' => 1,
]);
}
public function test_event_is_not_created_and_validation_error_messages_show()
{
$this->actingAs($this->test_user);
$organiser = factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$server = array('HTTP_X-Requested-With' => 'XMLHttpRequest');
$post = array(
'organiser_id' => $organiser->id,
);
$this->call('post', route('postCreateEvent'), $post, $server);
$this->seeJson([
'status' => 'error',
]);
}
public function test_event_can_be_edited()
{
$organiser = factory(App\Models\Organiser::class)->create(['account_id' => 1]);
$event = factory(App\Models\Event::class)->create([
'account_id' => $organiser->account_id,
'organiser_id' => $organiser->id,
'user_id' => $this->test_user->id,
]);
$this->actingAs($this->test_user)
->visit(route('showEventCustomize', ['event_id' => $event->id]))
->type($this->faker->text, 'title')
->type($this->faker->paragraph, 'description')
->press('Save Changes')
->seeJson([
'status' => 'success',
]);
}
}
``` | /content/code_sandbox/tests/deprecated/EventTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 608 |
```php
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|your_sha256_hash----------
| Default Log Channel
|your_sha256_hash----------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|your_sha256_hash----------
| Log Channels
|your_sha256_hash----------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
],
];
``` | /content/code_sandbox/config/logging.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 628 |
```php
<?php namespace Tests\Features;
use App\Models\Attendee;
use Tests\Concerns\OrganisationWithoutTax;
use Tests\TestCase;
class OrganisationWithoutTaxTest extends TestCase
{
use OrganisationWithoutTax;
public function setUp(): void
{
parent::setUp();
$this->withoutMiddleware([
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\FirstRunMiddleware::class,
]);
$this->setupOrganisationWithoutTax();
}
/**
* @test
*/
public function cancels_and_refunds_order_with_single_ticket()
{
// Setup single attendee order
[$order, $attendees] = $this->makeTicketOrder(1, 100.00);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 0.00,
'amount' => 100.00,
'amount_refunded' => 100.00,
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function cancels_and_refunds_order_with_multiple_tickets()
{
// Setup multiple attendee order but refund only 3 out of 5
[$order, $attendees] = $this->makeTicketOrder(5, 100.00);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
$attendeeIds[2],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 2,
'sales_volume' => 200.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 200.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 2,
],
'orders' => [
'organiser_booking_fee' => 0.00,
'amount' => 500.00,
'amount_refunded' => 300.00,
'is_partially_refunded' => true,
],
]);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
/**
* @test
*/
public function your_sha256_hashking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(1, 100.00, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 5.00,
'amount' => 100.00,
'amount_refunded' => 105.00,
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function your_sha256_hashbooking_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(5, 100.00, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
$attendeeIds[2],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 2,
'sales_volume' => 200.00,
'organiser_fees_volume' => 10.00,
],
'tickets' => [
'sales_volume' => 200.00,
'organiser_fees_volume' => 10.00,
'quantity_sold' => 2,
],
'orders' => [
'organiser_booking_fee' => 25.00,
'amount' => 500.00,
'amount_refunded' => 315.00,
'is_partially_refunded' => true,
],
]);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
/**
* @test
*/
public function your_sha256_hashfees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(1, 100.00, false, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [$attendeeIds[0]],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 0,
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
],
'tickets' => [
'sales_volume' => 0.00,
'organiser_fees_volume' => 0.00,
'quantity_sold' => 0,
],
'orders' => [
'organiser_booking_fee' => 2.50,
'amount' => 100.00,
'amount_refunded' => 102.50,
'is_refunded' => true,
],
'attendees' => [
'is_refunded' => true,
'is_cancelled' => true,
],
]);
}
/**
* @test
*/
public function your_sha256_hashng_fees()
{
// Setup single attendee order with % fees
[$order, $attendees] = $this->makeTicketOrder(5, 100.00, false, true);
$attendeeIds = $attendees->pluck('id')->toArray();
$response = $this->actingAs($this->getAccountUser())
->post("event/order/$order->id/cancel", [
'attendees' => [
$attendeeIds[0],
$attendeeIds[1],
$attendeeIds[2],
],
]);
// Check refund call works
$response->assertStatus(200);
// Assert database is correct after refund and cancel
$this->assertDatabaseHasMany([
'event_stats' => [
'tickets_sold' => 2,
'sales_volume' => 200.00,
'organiser_fees_volume' => 5.00,
],
'tickets' => [
'sales_volume' => 200.00,
'organiser_fees_volume' => 5.00,
'quantity_sold' => 2,
],
'orders' => [
'organiser_booking_fee' => 12.50,
'amount' => 500.00,
'amount_refunded' => 307.50,
'is_partially_refunded' => true,
],
]);
// Check that the the attendees are marked as refunded/cancelled
$this->assertTrue(Attendee::find($attendeeIds[0])->is_refunded);
$this->assertTrue(Attendee::find($attendeeIds[0])->is_cancelled);
// Last attendee in order will not be refunded and cancelled
$this->assertFalse(Attendee::find($attendeeIds[4])->is_refunded);
$this->assertFalse(Attendee::find($attendeeIds[4])->is_cancelled);
}
}
``` | /content/code_sandbox/tests/Feature/OrderCancellation/OrganisationWithoutTaxTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,422 |
```php
<?php
return [
'debug' => env('APP_DEBUG_PDF', false),
'binpath' => 'lib/',
'binfile' => env('WKHTML2PDF_BIN_FILE', 'wkhtmltopdf-amd64'),
'output_mode' => 'I',
];
``` | /content/code_sandbox/config/Wkhtml2pdf.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 66 |
```php
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Attendize\Utils;
class UserLoginTest extends TestCase
{
/**
* Test login page is successful
*
* @return void
*/
public function test_login_is_successful()
{
$this->visit(route('login'))
->type($this->test_user_email, 'email')
->type($this->test_user_password, 'password')
->press('Login')
->seePageIs(route('showCreateOrganiser', ['first_run' => '1']));
}
/**
* Test login page is unsuccessful with wrong password
*
* @return void
*/
public function test_login_is_unsuccessful_with_wrong_password()
{
$this->visit(route('login'))
->type($this->test_user_email, 'email')
->type('incorrect_password', 'password')
->press('Login')
->seePageIs(route('login'))
->see('Your username/password combination was incorrect');
}
/**
* Test login page is unsuccessful with wrong email address
*
* @return void
*/
public function test_login_is_unsuccessful_with_wrong_email_address()
{
$this->visit(route('login'))
->type('other@email.com', 'email')
->type($this->test_user_password, 'password')
->press('Login')
->seePageIs(route('login'))
->see('Your username/password combination was incorrect');
}
}
``` | /content/code_sandbox/tests/deprecated/UserLoginTest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 337 |
```php
<?php
/**
* Ok, glad you are here
* first we get a config instance, and set the settings
* $config = HTMLPurifier_Config::createDefault();
* $config->set('Core.Encoding', $this->config->get('purifier.encoding'));
* $config->set('Cache.SerializerPath', $this->config->get('purifier.cachePath'));
* if ( ! $this->config->get('purifier.finalize')) {
* $config->autoFinalize = false;
* }
* $config->loadArray($this->getConfig());.
*
* You must NOT delete the default settings
* anything in settings should be compacted with params that needed to instance HTMLPurifier_Config.
*
* @link path_to_url
*/
return [
'encoding' => 'UTF-8',
'finalize' => true,
'cachePath' => storage_path('app/purifier'),
'settings' => [
'default' => [
'HTML.Doctype' => 'HTML 4.01 Transitional',
'HTML.Allowed' => 'a[href|title],b,blockquote,br,code,dd,del,div,dl,dt,em,h1,h2,h3,h4,h5,h6,hr,i,img[width|height|alt|src],ins,kbd,li,ol,p,p[style],pre,q,s,samp,span[style],strike,strong,sub,sup,table[summary],tbody,td[abbr],tfoot,th[abbr],thead,tr,tt,ul,var',
'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
'AutoFormat.AutoParagraph' => true,
'AutoFormat.RemoveEmpty' => true,
'AutoFormat.Linkify' => true,
],
'strip_all' => [
'HTML.Allowed' => '',
],
'youtube' => [
'HTML.SafeIframe' => 'true',
'URI.SafeIframeRegexp' => '%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/)%',
],
],
];
``` | /content/code_sandbox/config/purifier.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 480 |
```php
<?php
namespace Tests;
use Hash;
use Illuminate\Contracts\Console\Kernel;
trait CreatesApplication
{
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
Hash::driver('bcrypt')->setRounds(4);
return $app;
}
}
``` | /content/code_sandbox/tests/CreatesApplication.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 97 |
```php
<?php
return [
/*
|your_sha256_hash----------
| Mail Driver
|your_sha256_hash----------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
'driver' => env('MAIL_DRIVER', 'smtp'),
/*
|your_sha256_hash----------
| SMTP Host Address
|your_sha256_hash----------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
/*
|your_sha256_hash----------
| SMTP Host Port
|your_sha256_hash----------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
'port' => env('MAIL_PORT', 587),
/*
|your_sha256_hash----------
| Global "From" Address
|your_sha256_hash----------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|your_sha256_hash----------
| E-Mail Encryption Protocol
|your_sha256_hash----------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
/*
|your_sha256_hash----------
| SMTP Server Username
|your_sha256_hash----------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
/*
|your_sha256_hash----------
| Sendmail System Path
|your_sha256_hash----------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|your_sha256_hash----------
| Markdown Mail Settings
|your_sha256_hash----------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
/*
|your_sha256_hash----------
| Log Channel
|your_sha256_hash----------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/
'log_channel' => env('MAIL_LOG_CHANNEL'),
];
``` | /content/code_sandbox/config/mail.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 903 |
```php
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
``` | /content/code_sandbox/server.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.