nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/histogram_filter/histogram_filter.py
map_shift
(grid_map, x_shift, y_shift)
return grid_map
174
186
def map_shift(grid_map, x_shift, y_shift): tmp_grid_map = copy.deepcopy(grid_map.data) for ix in range(grid_map.x_w): for iy in range(grid_map.y_w): nix = ix + x_shift niy = iy + y_shift if 0 <= nix < grid_map.x_w and 0 <= niy < grid_map.y_w: grid_map.data[ix + x_shift][iy + y_shift] =\ tmp_grid_map[ix][iy] return grid_map
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/histogram_filter/histogram_filter.py#L174-L186
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12 ]
92.307692
[]
0
false
90.410959
13
5
100
0
def map_shift(grid_map, x_shift, y_shift): tmp_grid_map = copy.deepcopy(grid_map.data) for ix in range(grid_map.x_w): for iy in range(grid_map.y_w): nix = ix + x_shift niy = iy + y_shift if 0 <= nix < grid_map.x_w and 0 <= niy < grid_map.y_w: grid_map.data[ix + x_shift][iy + y_shift] =\ tmp_grid_map[ix][iy] return grid_map
544
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/histogram_filter/histogram_filter.py
motion_update
(grid_map, u, yaw)
return grid_map
189
204
def motion_update(grid_map, u, yaw): grid_map.dx += DT * math.cos(yaw) * u[0] grid_map.dy += DT * math.sin(yaw) * u[0] x_shift = grid_map.dx // grid_map.xy_resolution y_shift = grid_map.dy // grid_map.xy_resolution if abs(x_shift) >= 1.0 or abs(y_shift) >= 1.0: # map should be shifted grid_map = map_shift(grid_map, int(x_shift), int(y_shift)) grid_map.dx -= x_shift * grid_map.xy_resolution grid_map.dy -= y_shift * grid_map.xy_resolution # Add motion noise grid_map.data = gaussian_filter(grid_map.data, sigma=MOTION_STD) return grid_map
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/histogram_filter/histogram_filter.py#L189-L204
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
90.410959
16
3
100
0
def motion_update(grid_map, u, yaw): grid_map.dx += DT * math.cos(yaw) * u[0] grid_map.dy += DT * math.sin(yaw) * u[0] x_shift = grid_map.dx // grid_map.xy_resolution y_shift = grid_map.dy // grid_map.xy_resolution if abs(x_shift) >= 1.0 or abs(y_shift) >= 1.0: # map should be shifted grid_map = map_shift(grid_map, int(x_shift), int(y_shift)) grid_map.dx -= x_shift * grid_map.xy_resolution grid_map.dy -= y_shift * grid_map.xy_resolution # Add motion noise grid_map.data = gaussian_filter(grid_map.data, sigma=MOTION_STD) return grid_map
545
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/histogram_filter/histogram_filter.py
calc_grid_index
(grid_map)
return mx, my
207
215
def calc_grid_index(grid_map): mx, my = np.mgrid[slice(grid_map.min_x - grid_map.xy_resolution / 2.0, grid_map.max_x + grid_map.xy_resolution / 2.0, grid_map.xy_resolution), slice(grid_map.min_y - grid_map.xy_resolution / 2.0, grid_map.max_y + grid_map.xy_resolution / 2.0, grid_map.xy_resolution)] return mx, my
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/histogram_filter/histogram_filter.py#L207-L215
2
[ 0, 1, 7, 8 ]
44.444444
[]
0
false
90.410959
9
1
100
0
def calc_grid_index(grid_map): mx, my = np.mgrid[slice(grid_map.min_x - grid_map.xy_resolution / 2.0, grid_map.max_x + grid_map.xy_resolution / 2.0, grid_map.xy_resolution), slice(grid_map.min_y - grid_map.xy_resolution / 2.0, grid_map.max_y + grid_map.xy_resolution / 2.0, grid_map.xy_resolution)] return mx, my
546
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/histogram_filter/histogram_filter.py
GridMap.__init__
(self)
46
56
def __init__(self): self.data = None self.xy_resolution = None self.min_x = None self.min_y = None self.max_x = None self.max_y = None self.x_w = None self.y_w = None self.dx = 0.0 # movement distance self.dy = 0.0
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/histogram_filter/histogram_filter.py#L46-L56
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
90.410959
11
1
100
0
def __init__(self): self.data = None self.xy_resolution = None self.min_x = None self.min_y = None self.max_x = None self.max_y = None self.x_w = None self.y_w = None self.dx = 0.0 # movement distance self.dy = 0.0
547
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
calc_input
()
return u
45
49
def calc_input(): v = 1.0 # [m/s] yawRate = 0.1 # [rad/s] u = np.array([[v, yawRate]]).T return u
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L45-L49
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
91.729323
5
1
100
0
def calc_input(): v = 1.0 # [m/s] yawRate = 0.1 # [rad/s] u = np.array([[v, yawRate]]).T return u
548
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
observation
(xTrue, xd, u)
return xTrue, z, xd, ud
52
63
def observation(xTrue, xd, u): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = observation_model(xTrue) + GPS_NOISE @ np.random.randn(2, 1) # add noise to input ud = u + INPUT_NOISE @ np.random.randn(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L52-L63
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
91.729323
12
1
100
0
def observation(xTrue, xd, u): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = observation_model(xTrue) + GPS_NOISE @ np.random.randn(2, 1) # add noise to input ud = u + INPUT_NOISE @ np.random.randn(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
549
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
motion_model
(x, u)
return x
66
79
def motion_model(x, u): F = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]]) B = np.array([[DT * math.cos(x[2]), 0], [DT * math.sin(x[2]), 0], [0.0, DT], [1.0, 0.0]]) x = F @ x + B @ u return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L66-L79
2
[ 0, 1, 5, 6, 10, 11, 12, 13 ]
57.142857
[]
0
false
91.729323
14
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]]) B = np.array([[DT * math.cos(x[2]), 0], [DT * math.sin(x[2]), 0], [0.0, DT], [1.0, 0.0]]) x = F @ x + B @ u return x
550
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
observation_model
(x)
return z
82
90
def observation_model(x): H = np.array([ [1, 0, 0, 0], [0, 1, 0, 0] ]) z = H @ x return z
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L82-L90
2
[ 0, 1, 5, 6, 7, 8 ]
66.666667
[]
0
false
91.729323
9
1
100
0
def observation_model(x): H = np.array([ [1, 0, 0, 0], [0, 1, 0, 0] ]) z = H @ x return z
551
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
generate_sigma_points
(xEst, PEst, gamma)
return sigma
93
105
def generate_sigma_points(xEst, PEst, gamma): sigma = xEst Psqrt = scipy.linalg.sqrtm(PEst) n = len(xEst[:, 0]) # Positive direction for i in range(n): sigma = np.hstack((sigma, xEst + gamma * Psqrt[:, i:i + 1])) # Negative direction for i in range(n): sigma = np.hstack((sigma, xEst - gamma * Psqrt[:, i:i + 1])) return sigma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L93-L105
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
91.729323
13
3
100
0
def generate_sigma_points(xEst, PEst, gamma): sigma = xEst Psqrt = scipy.linalg.sqrtm(PEst) n = len(xEst[:, 0]) # Positive direction for i in range(n): sigma = np.hstack((sigma, xEst + gamma * Psqrt[:, i:i + 1])) # Negative direction for i in range(n): sigma = np.hstack((sigma, xEst - gamma * Psqrt[:, i:i + 1])) return sigma
552
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
predict_sigma_motion
(sigma, u)
return sigma
Sigma Points prediction with motion model
Sigma Points prediction with motion model
108
115
def predict_sigma_motion(sigma, u): """ Sigma Points prediction with motion model """ for i in range(sigma.shape[1]): sigma[:, i:i + 1] = motion_model(sigma[:, i:i + 1], u) return sigma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L108-L115
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
91.729323
8
2
100
1
def predict_sigma_motion(sigma, u): for i in range(sigma.shape[1]): sigma[:, i:i + 1] = motion_model(sigma[:, i:i + 1], u) return sigma
553
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
predict_sigma_observation
(sigma)
return sigma
Sigma Points prediction with observation model
Sigma Points prediction with observation model
118
127
def predict_sigma_observation(sigma): """ Sigma Points prediction with observation model """ for i in range(sigma.shape[1]): sigma[0:2, i] = observation_model(sigma[:, i]) sigma = sigma[0:2, :] return sigma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L118-L127
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
91.729323
10
2
100
1
def predict_sigma_observation(sigma): for i in range(sigma.shape[1]): sigma[0:2, i] = observation_model(sigma[:, i]) sigma = sigma[0:2, :] return sigma
554
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
calc_sigma_covariance
(x, sigma, wc, Pi)
return P
130
136
def calc_sigma_covariance(x, sigma, wc, Pi): nSigma = sigma.shape[1] d = sigma - x[0:sigma.shape[0]] P = Pi for i in range(nSigma): P = P + wc[0, i] * d[:, i:i + 1] @ d[:, i:i + 1].T return P
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L130-L136
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
91.729323
7
2
100
0
def calc_sigma_covariance(x, sigma, wc, Pi): nSigma = sigma.shape[1] d = sigma - x[0:sigma.shape[0]] P = Pi for i in range(nSigma): P = P + wc[0, i] * d[:, i:i + 1] @ d[:, i:i + 1].T return P
555
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
calc_pxz
(sigma, x, z_sigma, zb, wc)
return P
139
148
def calc_pxz(sigma, x, z_sigma, zb, wc): nSigma = sigma.shape[1] dx = sigma - x dz = z_sigma - zb[0:2] P = np.zeros((dx.shape[0], dz.shape[0])) for i in range(nSigma): P = P + wc[0, i] * dx[:, i:i + 1] @ dz[:, i:i + 1].T return P
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L139-L148
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
91.729323
10
2
100
0
def calc_pxz(sigma, x, z_sigma, zb, wc): nSigma = sigma.shape[1] dx = sigma - x dz = z_sigma - zb[0:2] P = np.zeros((dx.shape[0], dz.shape[0])) for i in range(nSigma): P = P + wc[0, i] * dx[:, i:i + 1] @ dz[:, i:i + 1].T return P
556
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
ukf_estimation
(xEst, PEst, z, u, wm, wc, gamma)
return xEst, PEst
151
170
def ukf_estimation(xEst, PEst, z, u, wm, wc, gamma): # Predict sigma = generate_sigma_points(xEst, PEst, gamma) sigma = predict_sigma_motion(sigma, u) xPred = (wm @ sigma.T).T PPred = calc_sigma_covariance(xPred, sigma, wc, Q) # Update zPred = observation_model(xPred) y = z - zPred sigma = generate_sigma_points(xPred, PPred, gamma) zb = (wm @ sigma.T).T z_sigma = predict_sigma_observation(sigma) st = calc_sigma_covariance(zb, z_sigma, wc, R) Pxz = calc_pxz(sigma, xPred, z_sigma, zb, wc) K = Pxz @ np.linalg.inv(st) xEst = xPred + K @ y PEst = PPred - K @ st @ K.T return xEst, PEst
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L151-L170
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
91.729323
20
1
100
0
def ukf_estimation(xEst, PEst, z, u, wm, wc, gamma): # Predict sigma = generate_sigma_points(xEst, PEst, gamma) sigma = predict_sigma_motion(sigma, u) xPred = (wm @ sigma.T).T PPred = calc_sigma_covariance(xPred, sigma, wc, Q) # Update zPred = observation_model(xPred) y = z - zPred sigma = generate_sigma_points(xPred, PPred, gamma) zb = (wm @ sigma.T).T z_sigma = predict_sigma_observation(sigma) st = calc_sigma_covariance(zb, z_sigma, wc, R) Pxz = calc_pxz(sigma, xPred, z_sigma, zb, wc) K = Pxz @ np.linalg.inv(st) xEst = xPred + K @ y PEst = PPred - K @ st @ K.T return xEst, PEst
557
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
plot_covariance_ellipse
(xEst, PEst)
173
193
def plot_covariance_ellipse(xEst, PEst): # pragma: no cover Pxy = PEst[0:2, 0:2] eigval, eigvec = np.linalg.eig(Pxy) if eigval[0] >= eigval[1]: bigind = 0 smallind = 1 else: bigind = 1 smallind = 0 t = np.arange(0, 2 * math.pi + 0.1, 0.1) a = math.sqrt(eigval[bigind]) b = math.sqrt(eigval[smallind]) x = [a * math.cos(it) for it in t] y = [b * math.sin(it) for it in t] angle = math.atan2(eigvec[1, bigind], eigvec[0, bigind]) fx = rot_mat_2d(angle) @ np.array([x, y]) px = np.array(fx[0, :] + xEst[0, 0]).flatten() py = np.array(fx[1, :] + xEst[1, 0]).flatten() plt.plot(px, py, "--r")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L173-L193
2
[]
0
[]
0
false
91.729323
21
4
100
0
def plot_covariance_ellipse(xEst, PEst): # pragma: no cover Pxy = PEst[0:2, 0:2] eigval, eigvec = np.linalg.eig(Pxy) if eigval[0] >= eigval[1]: bigind = 0 smallind = 1 else: bigind = 1 smallind = 0 t = np.arange(0, 2 * math.pi + 0.1, 0.1) a = math.sqrt(eigval[bigind]) b = math.sqrt(eigval[smallind]) x = [a * math.cos(it) for it in t] y = [b * math.sin(it) for it in t] angle = math.atan2(eigvec[1, bigind], eigvec[0, bigind]) fx = rot_mat_2d(angle) @ np.array([x, y]) px = np.array(fx[0, :] + xEst[0, 0]).flatten() py = np.array(fx[1, :] + xEst[1, 0]).flatten() plt.plot(px, py, "--r")
558
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
setup_ukf
(nx)
return wm, wc, gamma
196
209
def setup_ukf(nx): lamb = ALPHA ** 2 * (nx + KAPPA) - nx # calculate weights wm = [lamb / (lamb + nx)] wc = [(lamb / (lamb + nx)) + (1 - ALPHA ** 2 + BETA)] for i in range(2 * nx): wm.append(1.0 / (2 * (nx + lamb))) wc.append(1.0 / (2 * (nx + lamb))) gamma = math.sqrt(nx + lamb) wm = np.array([wm]) wc = np.array([wc]) return wm, wc, gamma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L196-L209
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
91.729323
14
2
100
0
def setup_ukf(nx): lamb = ALPHA ** 2 * (nx + KAPPA) - nx # calculate weights wm = [lamb / (lamb + nx)] wc = [(lamb / (lamb + nx)) + (1 - ALPHA ** 2 + BETA)] for i in range(2 * nx): wm.append(1.0 / (2 * (nx + lamb))) wc.append(1.0 / (2 * (nx + lamb))) gamma = math.sqrt(nx + lamb) wm = np.array([wm]) wc = np.array([wc]) return wm, wc, gamma
559
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/unscented_kalman_filter/unscented_kalman_filter.py
main
()
212
260
def main(): print(__file__ + " start!!") nx = 4 # State Vector [x y yaw v]' xEst = np.zeros((nx, 1)) xTrue = np.zeros((nx, 1)) PEst = np.eye(nx) xDR = np.zeros((nx, 1)) # Dead reckoning wm, wc, gamma = setup_ukf(nx) # history hxEst = xEst hxTrue = xTrue hxDR = xTrue hz = np.zeros((2, 1)) time = 0.0 while SIM_TIME >= time: time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u) xEst, PEst = ukf_estimation(xEst, PEst, z, ud, wm, wc, gamma) # store data history hxEst = np.hstack((hxEst, xEst)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) hz = np.hstack((hz, z)) 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(hz[0, :], hz[1, :], ".g") plt.plot(np.array(hxTrue[0, :]).flatten(), np.array(hxTrue[1, :]).flatten(), "-b") plt.plot(np.array(hxDR[0, :]).flatten(), np.array(hxDR[1, :]).flatten(), "-k") plt.plot(np.array(hxEst[0, :]).flatten(), np.array(hxEst[1, :]).flatten(), "-r") plot_covariance_ellipse(xEst, PEst) plt.axis("equal") plt.grid(True) plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/unscented_kalman_filter/unscented_kalman_filter.py#L212-L260
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
69.387755
[ 34, 36, 38, 39, 41, 43, 45, 46, 47, 48 ]
20.408163
false
91.729323
49
3
79.591837
0
def main(): print(__file__ + " start!!") nx = 4 # State Vector [x y yaw v]' xEst = np.zeros((nx, 1)) xTrue = np.zeros((nx, 1)) PEst = np.eye(nx) xDR = np.zeros((nx, 1)) # Dead reckoning wm, wc, gamma = setup_ukf(nx) # history hxEst = xEst hxTrue = xTrue hxDR = xTrue hz = np.zeros((2, 1)) time = 0.0 while SIM_TIME >= time: time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u) xEst, PEst = ukf_estimation(xEst, PEst, z, ud, wm, wc, gamma) # store data history hxEst = np.hstack((hxEst, xEst)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) hz = np.hstack((hz, z)) 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(hz[0, :], hz[1, :], ".g") plt.plot(np.array(hxTrue[0, :]).flatten(), np.array(hxTrue[1, :]).flatten(), "-b") plt.plot(np.array(hxDR[0, :]).flatten(), np.array(hxDR[1, :]).flatten(), "-k") plt.plot(np.array(hxEst[0, :]).flatten(), np.array(hxEst[1, :]).flatten(), "-r") plot_covariance_ellipse(xEst, PEst) plt.axis("equal") plt.grid(True) plt.pause(0.001)
560
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
calc_input
()
return u
38
42
def calc_input(): v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([[v, yaw_rate]]).T return u
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L38-L42
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
88.888889
5
1
100
0
def calc_input(): v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([[v, yaw_rate]]).T return u
570
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
observation
(x_true, xd, u, rf_id)
return x_true, z, xd, ud
45
68
def observation(x_true, xd, u, rf_id): x_true = motion_model(x_true, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(rf_id[:, 0])): dx = x_true[0, 0] - rf_id[i, 0] dy = x_true[1, 0] - rf_id[i, 1] d = math.hypot(dx, dy) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise zi = np.array([[dn, rf_id[i, 0], rf_id[i, 1]]]) z = np.vstack((z, zi)) # add noise to input ud1 = u[0, 0] + np.random.randn() * R_sim[0, 0] ** 0.5 ud2 = u[1, 0] + np.random.randn() * R_sim[1, 1] ** 0.5 ud = np.array([[ud1, ud2]]).T xd = motion_model(xd, ud) return x_true, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L45-L68
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
100
[]
0
true
88.888889
24
3
100
0
def observation(x_true, xd, u, rf_id): x_true = motion_model(x_true, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(rf_id[:, 0])): dx = x_true[0, 0] - rf_id[i, 0] dy = x_true[1, 0] - rf_id[i, 1] d = math.hypot(dx, dy) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise zi = np.array([[dn, rf_id[i, 0], rf_id[i, 1]]]) z = np.vstack((z, zi)) # add noise to input ud1 = u[0, 0] + np.random.randn() * R_sim[0, 0] ** 0.5 ud2 = u[1, 0] + np.random.randn() * R_sim[1, 1] ** 0.5 ud = np.array([[ud1, ud2]]).T xd = motion_model(xd, ud) return x_true, z, xd, ud
571
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
motion_model
(x, u)
return x
71
84
def motion_model(x, u): F = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT], [1.0, 0.0]]) x = F.dot(x) + B.dot(u) return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L71-L84
2
[ 0, 1, 5, 6, 10, 11, 12, 13 ]
57.142857
[]
0
false
88.888889
14
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT], [1.0, 0.0]]) x = F.dot(x) + B.dot(u) return x
572
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
gauss_likelihood
(x, sigma)
return p
87
91
def gauss_likelihood(x, sigma): p = 1.0 / math.sqrt(2.0 * math.pi * sigma ** 2) * \ math.exp(-x ** 2 / (2 * sigma ** 2)) return p
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L87-L91
2
[ 0, 1, 3, 4 ]
80
[]
0
false
88.888889
5
1
100
0
def gauss_likelihood(x, sigma): p = 1.0 / math.sqrt(2.0 * math.pi * sigma ** 2) * \ math.exp(-x ** 2 / (2 * sigma ** 2)) return p
573
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
calc_covariance
(x_est, px, pw)
return cov
calculate covariance matrix see ipynb doc
calculate covariance matrix see ipynb doc
94
106
def calc_covariance(x_est, px, pw): """ calculate covariance matrix see ipynb doc """ cov = np.zeros((3, 3)) n_particle = px.shape[1] for i in range(n_particle): dx = (px[:, i:i + 1] - x_est)[0:3] cov += pw[0, i] * dx @ dx.T cov *= 1.0 / (1.0 - pw @ pw.T) return cov
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L94-L106
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
88.888889
13
2
100
2
def calc_covariance(x_est, px, pw): cov = np.zeros((3, 3)) n_particle = px.shape[1] for i in range(n_particle): dx = (px[:, i:i + 1] - x_est)[0:3] cov += pw[0, i] * dx @ dx.T cov *= 1.0 / (1.0 - pw @ pw.T) return cov
574
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
pf_localization
(px, pw, z, u)
return x_est, p_est, px, pw
Localization with Particle filter
Localization with Particle filter
109
143
def pf_localization(px, pw, z, u): """ Localization with Particle filter """ for ip in range(NP): x = np.array([px[:, ip]]).T w = pw[0, ip] # Predict with random input sampling ud1 = u[0, 0] + np.random.randn() * R[0, 0] ** 0.5 ud2 = u[1, 0] + np.random.randn() * R[1, 1] ** 0.5 ud = np.array([[ud1, ud2]]).T x = motion_model(x, ud) # Calc Importance Weight for i in range(len(z[:, 0])): dx = x[0, 0] - z[i, 1] dy = x[1, 0] - z[i, 2] pre_z = math.hypot(dx, dy) dz = pre_z - z[i, 0] w = w * gauss_likelihood(dz, math.sqrt(Q[0, 0])) px[:, ip] = x[:, 0] pw[0, ip] = w pw = pw / pw.sum() # normalize x_est = px.dot(pw.T) p_est = calc_covariance(x_est, px, pw) N_eff = 1.0 / (pw.dot(pw.T))[0, 0] # Effective particle number if N_eff < NTh: px, pw = re_sampling(px, pw) return x_est, p_est, px, pw
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L109-L143
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 ]
100
[]
0
true
88.888889
35
4
100
1
def pf_localization(px, pw, z, u): for ip in range(NP): x = np.array([px[:, ip]]).T w = pw[0, ip] # Predict with random input sampling ud1 = u[0, 0] + np.random.randn() * R[0, 0] ** 0.5 ud2 = u[1, 0] + np.random.randn() * R[1, 1] ** 0.5 ud = np.array([[ud1, ud2]]).T x = motion_model(x, ud) # Calc Importance Weight for i in range(len(z[:, 0])): dx = x[0, 0] - z[i, 1] dy = x[1, 0] - z[i, 2] pre_z = math.hypot(dx, dy) dz = pre_z - z[i, 0] w = w * gauss_likelihood(dz, math.sqrt(Q[0, 0])) px[:, ip] = x[:, 0] pw[0, ip] = w pw = pw / pw.sum() # normalize x_est = px.dot(pw.T) p_est = calc_covariance(x_est, px, pw) N_eff = 1.0 / (pw.dot(pw.T))[0, 0] # Effective particle number if N_eff < NTh: px, pw = re_sampling(px, pw) return x_est, p_est, px, pw
575
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
re_sampling
(px, pw)
return px, pw
low variance re-sampling
low variance re-sampling
146
164
def re_sampling(px, pw): """ low variance re-sampling """ w_cum = np.cumsum(pw) base = np.arange(0.0, 1.0, 1 / NP) re_sample_id = base + np.random.uniform(0, 1 / NP) indexes = [] ind = 0 for ip in range(NP): while re_sample_id[ip] > w_cum[ind]: ind += 1 indexes.append(ind) px = px[:, indexes] pw = np.zeros((1, NP)) + 1.0 / NP # init weight return px, pw
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L146-L164
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
88.888889
19
3
100
1
def re_sampling(px, pw): w_cum = np.cumsum(pw) base = np.arange(0.0, 1.0, 1 / NP) re_sample_id = base + np.random.uniform(0, 1 / NP) indexes = [] ind = 0 for ip in range(NP): while re_sample_id[ip] > w_cum[ind]: ind += 1 indexes.append(ind) px = px[:, indexes] pw = np.zeros((1, NP)) + 1.0 / NP # init weight return px, pw
576
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
plot_covariance_ellipse
(x_est, p_est)
167
199
def plot_covariance_ellipse(x_est, p_est): # pragma: no cover p_xy = p_est[0:2, 0:2] eig_val, eig_vec = np.linalg.eig(p_xy) if eig_val[0] >= eig_val[1]: big_ind = 0 small_ind = 1 else: big_ind = 1 small_ind = 0 t = np.arange(0, 2 * math.pi + 0.1, 0.1) # eig_val[big_ind] or eiq_val[small_ind] were occasionally negative # numbers extremely close to 0 (~10^-20), catch these cases and set the # respective variable to 0 try: a = math.sqrt(eig_val[big_ind]) except ValueError: a = 0 try: b = math.sqrt(eig_val[small_ind]) except ValueError: b = 0 x = [a * math.cos(it) for it in t] y = [b * math.sin(it) for it in t] angle = math.atan2(eig_vec[1, big_ind], eig_vec[0, big_ind]) fx = rot_mat_2d(angle) @ np.array([[x, y]]) px = np.array(fx[:, 0] + x_est[0, 0]).flatten() py = np.array(fx[:, 1] + x_est[1, 0]).flatten() plt.plot(px, py, "--r")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L167-L199
2
[]
0
[]
0
false
88.888889
33
6
100
0
def plot_covariance_ellipse(x_est, p_est): # pragma: no cover p_xy = p_est[0:2, 0:2] eig_val, eig_vec = np.linalg.eig(p_xy) if eig_val[0] >= eig_val[1]: big_ind = 0 small_ind = 1 else: big_ind = 1 small_ind = 0 t = np.arange(0, 2 * math.pi + 0.1, 0.1) # eig_val[big_ind] or eiq_val[small_ind] were occasionally negative # numbers extremely close to 0 (~10^-20), catch these cases and set the # respective variable to 0 try: a = math.sqrt(eig_val[big_ind]) except ValueError: a = 0 try: b = math.sqrt(eig_val[small_ind]) except ValueError: b = 0 x = [a * math.cos(it) for it in t] y = [b * math.sin(it) for it in t] angle = math.atan2(eig_vec[1, big_ind], eig_vec[0, big_ind]) fx = rot_mat_2d(angle) @ np.array([[x, y]]) px = np.array(fx[:, 0] + x_est[0, 0]).flatten() py = np.array(fx[:, 1] + x_est[1, 0]).flatten() plt.plot(px, py, "--r")
577
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Localization/particle_filter/particle_filter.py
main
()
202
259
def main(): print(__file__ + " start!!") time = 0.0 # RF_ID positions [x, y] rf_id = np.array([[10.0, 0.0], [10.0, 10.0], [0.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' x_est = np.zeros((4, 1)) x_true = np.zeros((4, 1)) px = np.zeros((4, NP)) # Particle store pw = np.zeros((1, NP)) + 1.0 / NP # Particle weight x_dr = np.zeros((4, 1)) # Dead reckoning # history h_x_est = x_est h_x_true = x_true h_x_dr = x_true while SIM_TIME >= time: time += DT u = calc_input() x_true, z, x_dr, ud = observation(x_true, x_dr, u, rf_id) x_est, PEst, px, pw = pf_localization(px, pw, z, ud) # store data history h_x_est = np.hstack((h_x_est, x_est)) h_x_dr = np.hstack((h_x_dr, x_dr)) h_x_true = np.hstack((h_x_true, x_true)) 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]) for i in range(len(z[:, 0])): plt.plot([x_true[0, 0], z[i, 1]], [x_true[1, 0], z[i, 2]], "-k") plt.plot(rf_id[:, 0], rf_id[:, 1], "*k") plt.plot(px[0, :], px[1, :], ".r") plt.plot(np.array(h_x_true[0, :]).flatten(), np.array(h_x_true[1, :]).flatten(), "-b") plt.plot(np.array(h_x_dr[0, :]).flatten(), np.array(h_x_dr[1, :]).flatten(), "-k") plt.plot(np.array(h_x_est[0, :]).flatten(), np.array(h_x_est[1, :]).flatten(), "-r") plot_covariance_ellipse(x_est, PEst) plt.axis("equal") plt.grid(True) plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Localization/particle_filter/particle_filter.py#L202-L259
2
[ 0, 1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37 ]
58.62069
[ 38, 40, 44, 45, 46, 47, 48, 50, 52, 54, 55, 56, 57 ]
22.413793
false
88.888889
58
4
77.586207
0
def main(): print(__file__ + " start!!") time = 0.0 # RF_ID positions [x, y] rf_id = np.array([[10.0, 0.0], [10.0, 10.0], [0.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' x_est = np.zeros((4, 1)) x_true = np.zeros((4, 1)) px = np.zeros((4, NP)) # Particle store pw = np.zeros((1, NP)) + 1.0 / NP # Particle weight x_dr = np.zeros((4, 1)) # Dead reckoning # history h_x_est = x_est h_x_true = x_true h_x_dr = x_true while SIM_TIME >= time: time += DT u = calc_input() x_true, z, x_dr, ud = observation(x_true, x_dr, u, rf_id) x_est, PEst, px, pw = pf_localization(px, pw, z, ud) # store data history h_x_est = np.hstack((h_x_est, x_est)) h_x_dr = np.hstack((h_x_dr, x_dr)) h_x_true = np.hstack((h_x_true, x_true)) 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]) for i in range(len(z[:, 0])): plt.plot([x_true[0, 0], z[i, 1]], [x_true[1, 0], z[i, 2]], "-k") plt.plot(rf_id[:, 0], rf_id[:, 1], "*k") plt.plot(px[0, :], px[1, :], ".r") plt.plot(np.array(h_x_true[0, :]).flatten(), np.array(h_x_true[1, :]).flatten(), "-b") plt.plot(np.array(h_x_dr[0, :]).flatten(), np.array(h_x_dr[1, :]).flatten(), "-k") plt.plot(np.array(h_x_est[0, :]).flatten(), np.array(h_x_est[1, :]).flatten(), "-r") plot_covariance_ellipse(x_est, PEst) plt.axis("equal") plt.grid(True) plt.pause(0.001)
578
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
main
()
32
67
def main(): x0 = np.array([ [0.0], [0.0], [0.3], [0.0] ]) x = np.copy(x0) time = 0.0 while sim_time > time: time += delta_t # calc control input opt_x, opt_delta_x, opt_theta, opt_delta_theta, opt_input = \ mpc_control(x) # get input u = opt_input[0] # simulate inverted pendulum cart x = simulation(x, u) if show_animation: plt.clf() px = float(x[0]) theta = float(x[2]) plot_cart(px, theta) plt.xlim([-5.0, 2.0]) plt.pause(0.001) print("Finish") print(f"x={float(x[0]):.2f} [m] , theta={math.degrees(x[2]):.2f} [deg]") if show_animation: plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L32-L67
2
[ 0, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 31, 32, 33, 34 ]
61.111111
[ 25, 26, 27, 28, 29, 30, 35 ]
19.444444
false
64.150943
36
4
80.555556
0
def main(): x0 = np.array([ [0.0], [0.0], [0.3], [0.0] ]) x = np.copy(x0) time = 0.0 while sim_time > time: time += delta_t # calc control input opt_x, opt_delta_x, opt_theta, opt_delta_theta, opt_input = \ mpc_control(x) # get input u = opt_input[0] # simulate inverted pendulum cart x = simulation(x, u) if show_animation: plt.clf() px = float(x[0]) theta = float(x[2]) plot_cart(px, theta) plt.xlim([-5.0, 2.0]) plt.pause(0.001) print("Finish") print(f"x={float(x[0]):.2f} [m] , theta={math.degrees(x[2]):.2f} [deg]") if show_animation: plt.show()
579
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
simulation
(x, u)
return x
70
74
def simulation(x, u): A, B = get_model_matrix() x = np.dot(A, x) + np.dot(B, u) return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L70-L74
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
64.150943
5
1
100
0
def simulation(x, u): A, B = get_model_matrix() x = np.dot(A, x) + np.dot(B, u) return x
580
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
mpc_control
(x0)
return ox, dx, theta, d_theta, ou
77
108
def mpc_control(x0): x = cvxpy.Variable((nx, T + 1)) u = cvxpy.Variable((nu, T)) A, B = get_model_matrix() cost = 0.0 constr = [] for t in range(T): cost += cvxpy.quad_form(x[:, t + 1], Q) cost += cvxpy.quad_form(u[:, t], R) constr += [x[:, t + 1] == A @ x[:, t] + B @ u[:, t]] constr += [x[:, 0] == x0[:, 0]] prob = cvxpy.Problem(cvxpy.Minimize(cost), constr) start = time.time() prob.solve(verbose=False) elapsed_time = time.time() - start print(f"calc time:{elapsed_time:.6f} [sec]") if prob.status == cvxpy.OPTIMAL: ox = get_numpy_array_from_matrix(x.value[0, :]) dx = get_numpy_array_from_matrix(x.value[1, :]) theta = get_numpy_array_from_matrix(x.value[2, :]) d_theta = get_numpy_array_from_matrix(x.value[3, :]) ou = get_numpy_array_from_matrix(u.value[0, :]) else: ox, dx, theta, d_theta, ou = None, None, None, None, None return ox, dx, theta, d_theta, ou
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L77-L108
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 30, 31 ]
93.75
[ 29 ]
3.125
false
64.150943
32
3
96.875
0
def mpc_control(x0): x = cvxpy.Variable((nx, T + 1)) u = cvxpy.Variable((nu, T)) A, B = get_model_matrix() cost = 0.0 constr = [] for t in range(T): cost += cvxpy.quad_form(x[:, t + 1], Q) cost += cvxpy.quad_form(u[:, t], R) constr += [x[:, t + 1] == A @ x[:, t] + B @ u[:, t]] constr += [x[:, 0] == x0[:, 0]] prob = cvxpy.Problem(cvxpy.Minimize(cost), constr) start = time.time() prob.solve(verbose=False) elapsed_time = time.time() - start print(f"calc time:{elapsed_time:.6f} [sec]") if prob.status == cvxpy.OPTIMAL: ox = get_numpy_array_from_matrix(x.value[0, :]) dx = get_numpy_array_from_matrix(x.value[1, :]) theta = get_numpy_array_from_matrix(x.value[2, :]) d_theta = get_numpy_array_from_matrix(x.value[3, :]) ou = get_numpy_array_from_matrix(u.value[0, :]) else: ox, dx, theta, d_theta, ou = None, None, None, None, None return ox, dx, theta, d_theta, ou
581
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
get_numpy_array_from_matrix
(x)
return np.array(x).flatten()
get build-in list from matrix
get build-in list from matrix
111
115
def get_numpy_array_from_matrix(x): """ get build-in list from matrix """ return np.array(x).flatten()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L111-L115
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
64.150943
5
1
100
1
def get_numpy_array_from_matrix(x): return np.array(x).flatten()
582
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
get_model_matrix
()
return A, B
118
135
def get_model_matrix(): A = np.array([ [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, m * g / M, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, g * (M + m) / (l_bar * M), 0.0] ]) A = np.eye(nx) + delta_t * A B = np.array([ [0.0], [1.0 / M], [0.0], [1.0 / (l_bar * M)] ]) B = delta_t * B return A, B
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L118-L135
2
[ 0, 1, 7, 8, 9, 15, 16, 17 ]
44.444444
[]
0
false
64.150943
18
1
100
0
def get_model_matrix(): A = np.array([ [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, m * g / M, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, g * (M + m) / (l_bar * M), 0.0] ]) A = np.eye(nx) + delta_t * A B = np.array([ [0.0], [1.0 / M], [0.0], [1.0 / (l_bar * M)] ]) B = delta_t * B return A, B
583
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
flatten
(a)
return np.array(a).flatten()
138
139
def flatten(a): return np.array(a).flatten()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L138-L139
2
[ 0 ]
50
[ 1 ]
50
false
64.150943
2
1
50
0
def flatten(a): return np.array(a).flatten()
584
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_mpc_control.py
plot_cart
(xt, theta)
142
183
def plot_cart(xt, theta): cart_w = 1.0 cart_h = 0.5 radius = 0.1 cx = np.array([-cart_w / 2.0, cart_w / 2.0, cart_w / 2.0, -cart_w / 2.0, -cart_w / 2.0]) cy = np.array([0.0, 0.0, cart_h, cart_h, 0.0]) cy += radius * 2.0 cx = cx + xt bx = np.array([0.0, l_bar * math.sin(-theta)]) bx += xt by = np.array([cart_h, l_bar * math.cos(-theta) + cart_h]) by += radius * 2.0 angles = np.arange(0.0, math.pi * 2.0, math.radians(3.0)) ox = np.array([radius * math.cos(a) for a in angles]) oy = np.array([radius * math.sin(a) for a in angles]) rwx = np.copy(ox) + cart_w / 4.0 + xt rwy = np.copy(oy) + radius lwx = np.copy(ox) - cart_w / 4.0 + xt lwy = np.copy(oy) + radius wx = np.copy(ox) + bx[-1] wy = np.copy(oy) + by[-1] plt.plot(flatten(cx), flatten(cy), "-b") plt.plot(flatten(bx), flatten(by), "-k") plt.plot(flatten(rwx), flatten(rwy), "-k") plt.plot(flatten(lwx), flatten(lwy), "-k") plt.plot(flatten(wx), flatten(wy), "-k") plt.title(f"x: {xt:.2f} , theta: {math.degrees(theta):.2f}") # 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.axis("equal")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_mpc_control.py#L142-L183
2
[ 0 ]
2.380952
[ 1, 2, 3, 5, 7, 8, 10, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, 24, 26, 27, 29, 30, 31, 32, 33, 34, 37, 41 ]
66.666667
false
64.150943
42
3
33.333333
0
def plot_cart(xt, theta): cart_w = 1.0 cart_h = 0.5 radius = 0.1 cx = np.array([-cart_w / 2.0, cart_w / 2.0, cart_w / 2.0, -cart_w / 2.0, -cart_w / 2.0]) cy = np.array([0.0, 0.0, cart_h, cart_h, 0.0]) cy += radius * 2.0 cx = cx + xt bx = np.array([0.0, l_bar * math.sin(-theta)]) bx += xt by = np.array([cart_h, l_bar * math.cos(-theta) + cart_h]) by += radius * 2.0 angles = np.arange(0.0, math.pi * 2.0, math.radians(3.0)) ox = np.array([radius * math.cos(a) for a in angles]) oy = np.array([radius * math.sin(a) for a in angles]) rwx = np.copy(ox) + cart_w / 4.0 + xt rwy = np.copy(oy) + radius lwx = np.copy(ox) - cart_w / 4.0 + xt lwy = np.copy(oy) + radius wx = np.copy(ox) + bx[-1] wy = np.copy(oy) + by[-1] plt.plot(flatten(cx), flatten(cy), "-b") plt.plot(flatten(bx), flatten(by), "-k") plt.plot(flatten(rwx), flatten(rwy), "-k") plt.plot(flatten(lwx), flatten(lwy), "-k") plt.plot(flatten(wx), flatten(wy), "-k") plt.title(f"x: {xt:.2f} , theta: {math.degrees(theta):.2f}") # 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.axis("equal")
585
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
main
()
31
62
def main(): x0 = np.array([ [0.0], [0.0], [0.3], [0.0] ]) x = np.copy(x0) time = 0.0 while sim_time > time: time += delta_t # calc control input u = lqr_control(x) # simulate inverted pendulum cart x = simulation(x, u) if show_animation: plt.clf() px = float(x[0]) theta = float(x[2]) plot_cart(px, theta) plt.xlim([-5.0, 2.0]) plt.pause(0.001) print("Finish") print(f"x={float(x[0]):.2f} [m] , theta={math.degrees(x[2]):.2f} [deg]") if show_animation: plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L31-L62
2
[ 0, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 27, 28, 29, 30 ]
62.5
[ 21, 22, 23, 24, 25, 26, 31 ]
21.875
false
62.376238
32
4
78.125
0
def main(): x0 = np.array([ [0.0], [0.0], [0.3], [0.0] ]) x = np.copy(x0) time = 0.0 while sim_time > time: time += delta_t # calc control input u = lqr_control(x) # simulate inverted pendulum cart x = simulation(x, u) if show_animation: plt.clf() px = float(x[0]) theta = float(x[2]) plot_cart(px, theta) plt.xlim([-5.0, 2.0]) plt.pause(0.001) print("Finish") print(f"x={float(x[0]):.2f} [m] , theta={math.degrees(x[2]):.2f} [deg]") if show_animation: plt.show()
586
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
simulation
(x, u)
return x
65
69
def simulation(x, u): A, B = get_model_matrix() x = A @ x + B @ u return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L65-L69
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
62.376238
5
1
100
0
def simulation(x, u): A, B = get_model_matrix() x = A @ x + B @ u return x
587
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
solve_DARE
(A, B, Q, R, maxiter=150, eps=0.01)
return Pn
Solve a discrete time_Algebraic Riccati equation (DARE)
Solve a discrete time_Algebraic Riccati equation (DARE)
72
85
def solve_DARE(A, B, Q, R, maxiter=150, eps=0.01): """ Solve a discrete time_Algebraic Riccati equation (DARE) """ P = Q for i in range(maxiter): Pn = A.T @ P @ A - A.T @ P @ B @ \ inv(R + B.T @ P @ B) @ B.T @ P @ A + Q if (abs(Pn - P)).max() < eps: break P = Pn return Pn
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L72-L85
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
62.376238
14
3
100
1
def solve_DARE(A, B, Q, R, maxiter=150, eps=0.01): P = Q for i in range(maxiter): Pn = A.T @ P @ A - A.T @ P @ B @ \ inv(R + B.T @ P @ B) @ B.T @ P @ A + Q if (abs(Pn - P)).max() < eps: break P = Pn return Pn
588
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
dlqr
(A, B, Q, R)
return K, P, eigVals
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
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
88
103
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 P = solve_DARE(A, B, Q, R) # compute the LQR gain K = inv(B.T @ P @ B + R) @ (B.T @ P @ A) eigVals, eigVecs = eig(A - B @ K) return K, P, eigVals
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L88-L103
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
62.376238
16
1
100
4
def dlqr(A, B, Q, R): # first, try to solve the ricatti equation P = solve_DARE(A, B, Q, R) # compute the LQR gain K = inv(B.T @ P @ B + R) @ (B.T @ P @ A) eigVals, eigVecs = eig(A - B @ K) return K, P, eigVals
589
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
lqr_control
(x)
return u
106
113
def lqr_control(x): A, B = get_model_matrix() start = time.time() K, _, _ = dlqr(A, B, Q, R) u = -K @ x elapsed_time = time.time() - start print(f"calc time:{elapsed_time:.6f} [sec]") return u
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L106-L113
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
62.376238
8
1
100
0
def lqr_control(x): A, B = get_model_matrix() start = time.time() K, _, _ = dlqr(A, B, Q, R) u = -K @ x elapsed_time = time.time() - start print(f"calc time:{elapsed_time:.6f} [sec]") return u
590
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
get_numpy_array_from_matrix
(x)
return np.array(x).flatten()
get build-in list from matrix
get build-in list from matrix
116
120
def get_numpy_array_from_matrix(x): """ get build-in list from matrix """ return np.array(x).flatten()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L116-L120
2
[ 0, 1, 2, 3 ]
80
[ 4 ]
20
false
62.376238
5
1
80
1
def get_numpy_array_from_matrix(x): return np.array(x).flatten()
591
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
get_model_matrix
()
return A, B
123
140
def get_model_matrix(): A = np.array([ [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, m * g / M, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, g * (M + m) / (l_bar * M), 0.0] ]) A = np.eye(nx) + delta_t * A B = np.array([ [0.0], [1.0 / M], [0.0], [1.0 / (l_bar * M)] ]) B = delta_t * B return A, B
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L123-L140
2
[ 0, 1, 7, 8, 9, 15, 16, 17 ]
44.444444
[]
0
false
62.376238
18
1
100
0
def get_model_matrix(): A = np.array([ [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, m * g / M, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, g * (M + m) / (l_bar * M), 0.0] ]) A = np.eye(nx) + delta_t * A B = np.array([ [0.0], [1.0 / M], [0.0], [1.0 / (l_bar * M)] ]) B = delta_t * B return A, B
592
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
flatten
(a)
return np.array(a).flatten()
143
144
def flatten(a): return np.array(a).flatten()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L143-L144
2
[ 0 ]
50
[ 1 ]
50
false
62.376238
2
1
50
0
def flatten(a): return np.array(a).flatten()
593
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/inverted_pendulum/inverted_pendulum_lqr_control.py
plot_cart
(xt, theta)
147
188
def plot_cart(xt, theta): cart_w = 1.0 cart_h = 0.5 radius = 0.1 cx = np.array([-cart_w / 2.0, cart_w / 2.0, cart_w / 2.0, -cart_w / 2.0, -cart_w / 2.0]) cy = np.array([0.0, 0.0, cart_h, cart_h, 0.0]) cy += radius * 2.0 cx = cx + xt bx = np.array([0.0, l_bar * math.sin(-theta)]) bx += xt by = np.array([cart_h, l_bar * math.cos(-theta) + cart_h]) by += radius * 2.0 angles = np.arange(0.0, math.pi * 2.0, math.radians(3.0)) ox = np.array([radius * math.cos(a) for a in angles]) oy = np.array([radius * math.sin(a) for a in angles]) rwx = np.copy(ox) + cart_w / 4.0 + xt rwy = np.copy(oy) + radius lwx = np.copy(ox) - cart_w / 4.0 + xt lwy = np.copy(oy) + radius wx = np.copy(ox) + bx[-1] wy = np.copy(oy) + by[-1] plt.plot(flatten(cx), flatten(cy), "-b") plt.plot(flatten(bx), flatten(by), "-k") plt.plot(flatten(rwx), flatten(rwy), "-k") plt.plot(flatten(lwx), flatten(lwy), "-k") plt.plot(flatten(wx), flatten(wy), "-k") plt.title(f"x: {xt:.2f} , theta: {math.degrees(theta):.2f}") # 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.axis("equal")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/inverted_pendulum/inverted_pendulum_lqr_control.py#L147-L188
2
[ 0 ]
2.380952
[ 1, 2, 3, 5, 7, 8, 10, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, 24, 26, 27, 29, 30, 31, 32, 33, 34, 37, 41 ]
66.666667
false
62.376238
42
3
33.333333
0
def plot_cart(xt, theta): cart_w = 1.0 cart_h = 0.5 radius = 0.1 cx = np.array([-cart_w / 2.0, cart_w / 2.0, cart_w / 2.0, -cart_w / 2.0, -cart_w / 2.0]) cy = np.array([0.0, 0.0, cart_h, cart_h, 0.0]) cy += radius * 2.0 cx = cx + xt bx = np.array([0.0, l_bar * math.sin(-theta)]) bx += xt by = np.array([cart_h, l_bar * math.cos(-theta) + cart_h]) by += radius * 2.0 angles = np.arange(0.0, math.pi * 2.0, math.radians(3.0)) ox = np.array([radius * math.cos(a) for a in angles]) oy = np.array([radius * math.sin(a) for a in angles]) rwx = np.copy(ox) + cart_w / 4.0 + xt rwy = np.copy(oy) + radius lwx = np.copy(ox) - cart_w / 4.0 + xt lwy = np.copy(oy) + radius wx = np.copy(ox) + bx[-1] wy = np.copy(oy) + by[-1] plt.plot(flatten(cx), flatten(cy), "-b") plt.plot(flatten(bx), flatten(by), "-k") plt.plot(flatten(rwx), flatten(rwy), "-k") plt.plot(flatten(lwx), flatten(lwy), "-k") plt.plot(flatten(wx), flatten(wy), "-k") plt.title(f"x: {xt:.2f} , theta: {math.degrees(theta):.2f}") # 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.axis("equal")
594
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
move_to_pose
(x_start, y_start, theta_start, x_goal, y_goal, theta_goal)
97
134
def move_to_pose(x_start, y_start, theta_start, x_goal, y_goal, theta_goal): x = x_start y = y_start theta = theta_start x_diff = x_goal - x y_diff = y_goal - y x_traj, y_traj = [], [] rho = np.hypot(x_diff, y_diff) while rho > 0.001: x_traj.append(x) y_traj.append(y) x_diff = x_goal - x y_diff = y_goal - y rho, v, w = controller.calc_control_command( x_diff, y_diff, theta, theta_goal) if abs(v) > MAX_LINEAR_SPEED: v = np.sign(v) * MAX_LINEAR_SPEED if abs(w) > MAX_ANGULAR_SPEED: w = np.sign(w) * MAX_ANGULAR_SPEED theta = theta + w * dt x = x + v * np.cos(theta) * dt y = y + v * np.sin(theta) * dt if show_animation: # pragma: no cover plt.cla() plt.arrow(x_start, y_start, np.cos(theta_start), np.sin(theta_start), color='r', width=0.1) plt.arrow(x_goal, y_goal, np.cos(theta_goal), np.sin(theta_goal), color='g', width=0.1) plot_vehicle(x, y, theta, x_traj, y_traj)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L97-L134
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]
90.909091
[]
0
false
96.551724
38
5
100
0
def move_to_pose(x_start, y_start, theta_start, x_goal, y_goal, theta_goal): x = x_start y = y_start theta = theta_start x_diff = x_goal - x y_diff = y_goal - y x_traj, y_traj = [], [] rho = np.hypot(x_diff, y_diff) while rho > 0.001: x_traj.append(x) y_traj.append(y) x_diff = x_goal - x y_diff = y_goal - y rho, v, w = controller.calc_control_command( x_diff, y_diff, theta, theta_goal) if abs(v) > MAX_LINEAR_SPEED: v = np.sign(v) * MAX_LINEAR_SPEED if abs(w) > MAX_ANGULAR_SPEED: w = np.sign(w) * MAX_ANGULAR_SPEED theta = theta + w * dt x = x + v * np.cos(theta) * dt y = y + v * np.sin(theta) * dt if show_animation: # pragma: no cover plt.cla() plt.arrow(x_start, y_start, np.cos(theta_start), np.sin(theta_start), color='r', width=0.1) plt.arrow(x_goal, y_goal, np.cos(theta_goal), np.sin(theta_goal), color='g', width=0.1) plot_vehicle(x, y, theta, x_traj, y_traj)
603
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
plot_vehicle
(x, y, theta, x_traj, y_traj)
137
162
def plot_vehicle(x, y, theta, x_traj, y_traj): # pragma: no cover # Corners of triangular vehicle when pointing to the right (0 radians) p1_i = np.array([0.5, 0, 1]).T p2_i = np.array([-0.5, 0.25, 1]).T p3_i = np.array([-0.5, -0.25, 1]).T T = transformation_matrix(x, y, theta) p1 = np.matmul(T, p1_i) p2 = np.matmul(T, p2_i) p3 = np.matmul(T, p3_i) plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k-') plt.plot([p2[0], p3[0]], [p2[1], p3[1]], 'k-') plt.plot([p3[0], p1[0]], [p3[1], p1[1]], 'k-') plt.plot(x_traj, y_traj, 'b--') # 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.xlim(0, 20) plt.ylim(0, 20) plt.pause(dt)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L137-L162
2
[]
0
[]
0
false
96.551724
26
1
100
0
def plot_vehicle(x, y, theta, x_traj, y_traj): # pragma: no cover # Corners of triangular vehicle when pointing to the right (0 radians) p1_i = np.array([0.5, 0, 1]).T p2_i = np.array([-0.5, 0.25, 1]).T p3_i = np.array([-0.5, -0.25, 1]).T T = transformation_matrix(x, y, theta) p1 = np.matmul(T, p1_i) p2 = np.matmul(T, p2_i) p3 = np.matmul(T, p3_i) plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'k-') plt.plot([p2[0], p3[0]], [p2[1], p3[1]], 'k-') plt.plot([p3[0], p1[0]], [p3[1], p1[1]], 'k-') plt.plot(x_traj, y_traj, 'b--') # 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.xlim(0, 20) plt.ylim(0, 20) plt.pause(dt)
604
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
transformation_matrix
(x, y, theta)
return np.array([ [np.cos(theta), -np.sin(theta), x], [np.sin(theta), np.cos(theta), y], [0, 0, 1] ])
165
170
def transformation_matrix(x, y, theta): return np.array([ [np.cos(theta), -np.sin(theta), x], [np.sin(theta), np.cos(theta), y], [0, 0, 1] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L165-L170
2
[ 0 ]
16.666667
[ 1 ]
16.666667
false
96.551724
6
1
83.333333
0
def transformation_matrix(x, y, theta): return np.array([ [np.cos(theta), -np.sin(theta), x], [np.sin(theta), np.cos(theta), y], [0, 0, 1] ])
605
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
main
()
173
186
def main(): for i in range(5): x_start = 20 * random() y_start = 20 * random() theta_start = 2 * np.pi * random() - np.pi x_goal = 20 * random() y_goal = 20 * random() theta_goal = 2 * np.pi * random() - np.pi print("Initial x: %.2f m\nInitial y: %.2f m\nInitial theta: %.2f rad\n" % (x_start, y_start, theta_start)) print("Goal x: %.2f m\nGoal y: %.2f m\nGoal theta: %.2f rad\n" % (x_goal, y_goal, theta_goal)) move_to_pose(x_start, y_start, theta_start, x_goal, y_goal, theta_goal)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L173-L186
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13 ]
85.714286
[]
0
false
96.551724
14
2
100
0
def main(): for i in range(5): x_start = 20 * random() y_start = 20 * random() theta_start = 2 * np.pi * random() - np.pi x_goal = 20 * random() y_goal = 20 * random() theta_goal = 2 * np.pi * random() - np.pi print("Initial x: %.2f m\nInitial y: %.2f m\nInitial theta: %.2f rad\n" % (x_start, y_start, theta_start)) print("Goal x: %.2f m\nGoal y: %.2f m\nGoal theta: %.2f rad\n" % (x_goal, y_goal, theta_goal)) move_to_pose(x_start, y_start, theta_start, x_goal, y_goal, theta_goal)
606
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
PathFinderController.__init__
(self, Kp_rho, Kp_alpha, Kp_beta)
33
36
def __init__(self, Kp_rho, Kp_alpha, Kp_beta): self.Kp_rho = Kp_rho self.Kp_alpha = Kp_alpha self.Kp_beta = Kp_beta
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L33-L36
2
[ 0, 1, 2, 3 ]
100
[]
0
true
96.551724
4
1
100
0
def __init__(self, Kp_rho, Kp_alpha, Kp_beta): self.Kp_rho = Kp_rho self.Kp_alpha = Kp_alpha self.Kp_beta = Kp_beta
607
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
Control/move_to_pose/move_to_pose.py
PathFinderController.calc_control_command
(self, x_diff, y_diff, theta, theta_goal)
return rho, v, w
Returns the control command for the linear and angular velocities as well as the distance to goal Parameters ---------- x_diff : The position of target with respect to current robot position in x direction y_diff : The position of target with respect to current robot position in y direction theta : The current heading angle of robot with respect to x axis theta_goal: The target angle of robot with respect to x axis Returns ------- rho : The distance between the robot and the goal position v : Command linear velocity w : Command angular velocity
Returns the control command for the linear and angular velocities as well as the distance to goal
38
83
def calc_control_command(self, x_diff, y_diff, theta, theta_goal): """ Returns the control command for the linear and angular velocities as well as the distance to goal Parameters ---------- x_diff : The position of target with respect to current robot position in x direction y_diff : The position of target with respect to current robot position in y direction theta : The current heading angle of robot with respect to x axis theta_goal: The target angle of robot with respect to x axis Returns ------- rho : The distance between the robot and the goal position v : Command linear velocity w : Command angular velocity """ # Description of local variables: # - alpha is the angle to the goal relative to the heading of the robot # - beta is the angle between the robot's position and the goal # position plus the goal angle # - Kp_rho*rho and Kp_alpha*alpha drive the robot along a line towards # the goal # - Kp_beta*beta rotates the line so that it is parallel to the goal # angle # # Note: # we restrict alpha and beta (angle differences) to the range # [-pi, pi] to prevent unstable behavior e.g. difference going # from 0 rad to 2*pi rad with slight turn rho = np.hypot(x_diff, y_diff) alpha = (np.arctan2(y_diff, x_diff) - theta + np.pi) % (2 * np.pi) - np.pi beta = (theta_goal - theta - alpha + np.pi) % (2 * np.pi) - np.pi v = self.Kp_rho * rho w = self.Kp_alpha * alpha - controller.Kp_beta * beta if alpha > np.pi / 2 or alpha < -np.pi / 2: v = -v return rho, v, w
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/Control/move_to_pose/move_to_pose.py#L38-L83
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]
100
[]
0
true
96.551724
46
3
100
17
def calc_control_command(self, x_diff, y_diff, theta, theta_goal): # Description of local variables: # - alpha is the angle to the goal relative to the heading of the robot # - beta is the angle between the robot's position and the goal # position plus the goal angle # - Kp_rho*rho and Kp_alpha*alpha drive the robot along a line towards # the goal # - Kp_beta*beta rotates the line so that it is parallel to the goal # angle # # Note: # we restrict alpha and beta (angle differences) to the range # [-pi, pi] to prevent unstable behavior e.g. difference going # from 0 rad to 2*pi rad with slight turn rho = np.hypot(x_diff, y_diff) alpha = (np.arctan2(y_diff, x_diff) - theta + np.pi) % (2 * np.pi) - np.pi beta = (theta_goal - theta - alpha + np.pi) % (2 * np.pi) - np.pi v = self.Kp_rho * rho w = self.Kp_alpha * alpha - controller.Kp_beta * beta if alpha > np.pi / 2 or alpha < -np.pi / 2: v = -v return rho, v, w
608
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
utils/plot.py
plot_arrow
(x, y, yaw, arrow_length=1.0, origin_point_plot_style="xr", head_width=0.1, fc="r", ec="k", **kwargs)
Plot an arrow or arrows based on 2D state (x, y, yaw) All optional settings of matplotlib.pyplot.arrow can be used. - matplotlib.pyplot.arrow: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.arrow.html Parameters ---------- x : a float or array_like a value or a list of arrow origin x position. y : a float or array_like a value or a list of arrow origin y position. yaw : a float or array_like a value or a list of arrow yaw angle (orientation). arrow_length : a float (optional) arrow length. default is 1.0 origin_point_plot_style : str (optional) origin point plot style. If None, not plotting. head_width : a float (optional) arrow head width. default is 0.1 fc : string (optional) face color ec : string (optional) edge color
Plot an arrow or arrows based on 2D state (x, y, yaw)
9
50
def plot_arrow(x, y, yaw, arrow_length=1.0, origin_point_plot_style="xr", head_width=0.1, fc="r", ec="k", **kwargs): """ Plot an arrow or arrows based on 2D state (x, y, yaw) All optional settings of matplotlib.pyplot.arrow can be used. - matplotlib.pyplot.arrow: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.arrow.html Parameters ---------- x : a float or array_like a value or a list of arrow origin x position. y : a float or array_like a value or a list of arrow origin y position. yaw : a float or array_like a value or a list of arrow yaw angle (orientation). arrow_length : a float (optional) arrow length. default is 1.0 origin_point_plot_style : str (optional) origin point plot style. If None, not plotting. head_width : a float (optional) arrow head width. default is 0.1 fc : string (optional) face color ec : string (optional) edge color """ 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, head_width=head_width, fc=fc, ec=ec, **kwargs) else: plt.arrow(x, y, arrow_length * math.cos(yaw), arrow_length * math.sin(yaw), head_width=head_width, fc=fc, ec=ec, **kwargs) if origin_point_plot_style is not None: plt.plot(x, y, origin_point_plot_style)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/utils/plot.py#L9-L50
2
[ 0 ]
2.380952
[ 29, 30, 31, 34, 40, 41 ]
14.285714
false
31.25
42
4
85.714286
24
def plot_arrow(x, y, yaw, arrow_length=1.0, origin_point_plot_style="xr", head_width=0.1, fc="r", ec="k", **kwargs): 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, head_width=head_width, fc=fc, ec=ec, **kwargs) else: plt.arrow(x, y, arrow_length * math.cos(yaw), arrow_length * math.sin(yaw), head_width=head_width, fc=fc, ec=ec, **kwargs) if origin_point_plot_style is not None: plt.plot(x, y, origin_point_plot_style)
609
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
utils/plot.py
plot_curvature
(x_list, y_list, heading_list, curvature, k=0.01, c="-c", label="Curvature")
Plot curvature on 2D path. This plot is a line from the original path, the lateral distance from the original path shows curvature magnitude. Left turning shows right side plot, right turning shows left side plot. For straight path, the curvature plot will be on the path, because curvature is 0 on the straight path. Parameters ---------- x_list : array_like x position list of the path y_list : array_like y position list of the path heading_list : array_like heading list of the path curvature : array_like curvature list of the path k : float curvature scale factor to calculate distance from the original path c : string color of the plot label : string label of the plot
Plot curvature on 2D path. This plot is a line from the original path, the lateral distance from the original path shows curvature magnitude. Left turning shows right side plot, right turning shows left side plot. For straight path, the curvature plot will be on the path, because curvature is 0 on the straight path.
53
86
def plot_curvature(x_list, y_list, heading_list, curvature, k=0.01, c="-c", label="Curvature"): """ Plot curvature on 2D path. This plot is a line from the original path, the lateral distance from the original path shows curvature magnitude. Left turning shows right side plot, right turning shows left side plot. For straight path, the curvature plot will be on the path, because curvature is 0 on the straight path. Parameters ---------- x_list : array_like x position list of the path y_list : array_like y position list of the path heading_list : array_like heading list of the path curvature : array_like curvature list of the path k : float curvature scale factor to calculate distance from the original path c : string color of the plot label : string label of the plot """ cx = [x + d * k * np.cos(yaw - np.pi / 2.0) for x, y, yaw, d in zip(x_list, y_list, heading_list, curvature)] cy = [y + d * k * np.sin(yaw - np.pi / 2.0) for x, y, yaw, d in zip(x_list, y_list, heading_list, curvature)] plt.plot(cx, cy, c, label=label) for ix, iy, icx, icy in zip(x_list, y_list, cx, cy): plt.plot([ix, icx], [iy, icy], c)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/utils/plot.py#L53-L86
2
[ 0 ]
2.941176
[ 26, 28, 31, 32, 33 ]
14.705882
false
31.25
34
4
85.294118
22
def plot_curvature(x_list, y_list, heading_list, curvature, k=0.01, c="-c", label="Curvature"): cx = [x + d * k * np.cos(yaw - np.pi / 2.0) for x, y, yaw, d in zip(x_list, y_list, heading_list, curvature)] cy = [y + d * k * np.sin(yaw - np.pi / 2.0) for x, y, yaw, d in zip(x_list, y_list, heading_list, curvature)] plt.plot(cx, cy, c, label=label) for ix, iy, icx, icy in zip(x_list, y_list, cx, cy): plt.plot([ix, icx], [iy, icy], c)
610
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
utils/angle.py
rot_mat_2d
(angle)
return Rot.from_euler('z', angle).as_matrix()[0:2, 0:2]
Create 2D rotation matrix from an angle Parameters ---------- angle : Returns ------- A 2D rotation matrix Examples -------- >>> angle_mod(-4.0)
Create 2D rotation matrix from an angle
5
23
def rot_mat_2d(angle): """ Create 2D rotation matrix from an angle Parameters ---------- angle : Returns ------- A 2D rotation matrix Examples -------- >>> angle_mod(-4.0) """ return Rot.from_euler('z', angle).as_matrix()[0:2, 0:2]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/utils/angle.py#L5-L23
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
100
19
1
100
13
def rot_mat_2d(angle): return Rot.from_euler('z', angle).as_matrix()[0:2, 0:2]
611
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
utils/angle.py
angle_mod
(x, zero_2_2pi=False, degree=False)
Angle modulo operation Default angle modulo range is [-pi, pi) Parameters ---------- x : float or array_like A angle or an array of angles. This array is flattened for the calculation. When an angle is provided, a float angle is returned. zero_2_2pi : bool, optional Change angle modulo range to [0, 2pi) Default is False. degree : bool, optional If True, then the given angles are assumed to be in degrees. Default is False. Returns ------- ret : float or ndarray an angle or an array of modulated angle. Examples -------- >>> angle_mod(-4.0) 2.28318531 >>> angle_mod([-4.0]) np.array(2.28318531) >>> angle_mod([-150.0, 190.0, 350], degree=True) array([-150., -170., -10.]) >>> angle_mod(-60.0, zero_2_2pi=True, degree=True) array([300.])
Angle modulo operation Default angle modulo range is [-pi, pi)
26
83
def angle_mod(x, zero_2_2pi=False, degree=False): """ Angle modulo operation Default angle modulo range is [-pi, pi) Parameters ---------- x : float or array_like A angle or an array of angles. This array is flattened for the calculation. When an angle is provided, a float angle is returned. zero_2_2pi : bool, optional Change angle modulo range to [0, 2pi) Default is False. degree : bool, optional If True, then the given angles are assumed to be in degrees. Default is False. Returns ------- ret : float or ndarray an angle or an array of modulated angle. Examples -------- >>> angle_mod(-4.0) 2.28318531 >>> angle_mod([-4.0]) np.array(2.28318531) >>> angle_mod([-150.0, 190.0, 350], degree=True) array([-150., -170., -10.]) >>> angle_mod(-60.0, zero_2_2pi=True, degree=True) array([300.]) """ if isinstance(x, float): is_float = True else: is_float = False x = np.asarray(x).flatten() if degree: x = np.deg2rad(x) if zero_2_2pi: mod_angle = x % (2 * np.pi) else: mod_angle = (x + np.pi) % (2 * np.pi) - np.pi if degree: mod_angle = np.rad2deg(mod_angle) if is_float: return mod_angle.item() else: return mod_angle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/utils/angle.py#L26-L83
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 ]
100
[]
0
true
100
58
6
100
33
def angle_mod(x, zero_2_2pi=False, degree=False): if isinstance(x, float): is_float = True else: is_float = False x = np.asarray(x).flatten() if degree: x = np.deg2rad(x) if zero_2_2pi: mod_angle = x % (2 * np.pi) else: mod_angle = (x + np.pi) % (2 * np.pi) - np.pi if degree: mod_angle = np.rad2deg(mod_angle) if is_float: return mod_angle.item() else: return mod_angle
612
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
update
(state, a, delta)
return state
42
54
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L42-L54
2
[ 0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 12 ]
84.615385
[ 3, 5 ]
15.384615
false
89.542484
13
3
84.615385
0
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
613
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
PIDControl
(target, current)
return a
57
60
def PIDControl(target, current): a = Kp * (target - current) return a
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L57-L60
2
[ 0, 1, 2, 3 ]
100
[]
0
true
89.542484
4
1
100
0
def PIDControl(target, current): a = Kp * (target - current) return a
614
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
63
64
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L63-L64
2
[ 0, 1 ]
100
[]
0
true
89.542484
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
615
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
solve_DARE
(A, B, Q, R)
return Xn
solve a discrete time_Algebraic Riccati equation (DARE)
solve a discrete time_Algebraic Riccati equation (DARE)
67
82
def solve_DARE(A, B, Q, R): """ solve a discrete time_Algebraic Riccati equation (DARE) """ X = Q maxiter = 150 eps = 0.01 for i in range(maxiter): 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() < eps: break X = Xn return Xn
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L67-L82
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
89.542484
16
3
100
1
def solve_DARE(A, B, Q, R): X = Q maxiter = 150 eps = 0.01 for i in range(maxiter): 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() < eps: break X = Xn return Xn
616
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
dlqr
(A, B, Q, R)
return K, X, eigVals
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
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
85
100
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) eigVals, eigVecs = la.eig(A - B @ K) return K, X, eigVals
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L85-L100
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
89.542484
16
1
100
4
def dlqr(A, B, Q, R): # 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) eigVals, eigVecs = la.eig(A - B @ K) return K, X, eigVals
617
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
lqr_steering_control
(state, cx, cy, cyaw, ck, pe, pth_e)
return delta, ind, e, th_e
103
135
def lqr_steering_control(state, cx, cy, cyaw, ck, pe, pth_e): ind, e = calc_nearest_index(state, cx, cy, cyaw) k = ck[ind] v = state.v th_e = pi_2_pi(state.yaw - cyaw[ind]) A = np.zeros((4, 4)) A[0, 0] = 1.0 A[0, 1] = dt A[1, 2] = v A[2, 2] = 1.0 A[2, 3] = dt # print(A) B = np.zeros((4, 1)) B[3, 0] = v / L K, _, _ = dlqr(A, B, Q, R) x = np.zeros((4, 1)) x[0, 0] = e x[1, 0] = (e - pe) / dt x[2, 0] = th_e x[3, 0] = (th_e - pth_e) / dt ff = math.atan2(L * k, 1) fb = pi_2_pi((-K @ x)[0, 0]) delta = ff + fb return delta, ind, e, th_e
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L103-L135
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
100
[]
0
true
89.542484
33
1
100
0
def lqr_steering_control(state, cx, cy, cyaw, ck, pe, pth_e): ind, e = calc_nearest_index(state, cx, cy, cyaw) k = ck[ind] v = state.v th_e = pi_2_pi(state.yaw - cyaw[ind]) A = np.zeros((4, 4)) A[0, 0] = 1.0 A[0, 1] = dt A[1, 2] = v A[2, 2] = 1.0 A[2, 3] = dt # print(A) B = np.zeros((4, 1)) B[3, 0] = v / L K, _, _ = dlqr(A, B, Q, R) x = np.zeros((4, 1)) x[0, 0] = e x[1, 0] = (e - pe) / dt x[2, 0] = th_e x[3, 0] = (th_e - pth_e) / dt ff = math.atan2(L * k, 1) fb = pi_2_pi((-K @ x)[0, 0]) delta = ff + fb return delta, ind, e, th_e
618
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
calc_nearest_index
(state, cx, cy, cyaw)
return ind, mind
138
157
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L138-L157
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
89.542484
20
5
100
0
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
619
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
closed_loop_prediction
(cx, cy, cyaw, ck, speed_profile, goal)
return t, x, y, yaw, v
160
215
def closed_loop_prediction(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 = lqr_steering_control( state, cx, cy, cyaw, ck, e, e_th) ai = PIDControl(speed_profile[target_ind], state.v) 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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L160-L215
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 54, 55 ]
75
[ 24, 42, 44, 46, 47, 48, 49, 50, 51, 53 ]
17.857143
false
89.542484
56
6
82.142857
0
def closed_loop_prediction(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 = lqr_steering_control( state, cx, cy, cyaw, ck, e, e_th) ai = PIDControl(speed_profile[target_ind], state.v) 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
620
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
calc_speed_profile
(cx, cy, cyaw, target_speed)
return speed_profile
218
241
def calc_speed_profile(cx, cy, cyaw, target_speed): speed_profile = [target_speed] * len(cx) direction = 1.0 # Set stop point for i in range(len(cx) - 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_profile[-1] = 0.0 return speed_profile
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L218-L241
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 16, 17, 18, 20, 21, 22, 23 ]
83.333333
[ 11, 14, 19 ]
12.5
false
89.542484
24
5
87.5
0
def calc_speed_profile(cx, cy, cyaw, target_speed): speed_profile = [target_speed] * len(cx) direction = 1.0 # Set stop point for i in range(len(cx) - 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_profile[-1] = 0.0 return speed_profile
621
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
main
()
244
284
def main(): print("LQR steering control tracking start!!") ax = [0.0, 6.0, 12.5, 10.0, 7.5, 3.0, -1.0] ay = [0.0, -3.0, -5.0, 6.5, 3.0, 5.0, -2.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(cx, cy, cyaw, target_speed) t, x, y, yaw, v = closed_loop_prediction(cx, cy, cyaw, ck, sp, goal) if show_animation: # pragma: no cover plt.close() plt.subplots(1) plt.plot(ax, ay, "xb", label="input") plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots(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()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L244-L284
2
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13 ]
76.470588
[]
0
false
89.542484
41
3
100
0
def main(): print("LQR steering control tracking start!!") ax = [0.0, 6.0, 12.5, 10.0, 7.5, 3.0, -1.0] ay = [0.0, -3.0, -5.0, 6.5, 3.0, 5.0, -2.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(cx, cy, cyaw, target_speed) t, x, y, yaw, v = closed_loop_prediction(cx, cy, cyaw, ck, sp, goal) if show_animation: # pragma: no cover plt.close() plt.subplots(1) plt.plot(ax, ay, "xb", label="input") plt.plot(cx, cy, "-r", label="spline") plt.plot(x, y, "-g", label="tracking") plt.grid(True) plt.axis("equal") plt.xlabel("x[m]") plt.ylabel("y[m]") plt.legend() plt.subplots(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()
622
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_steer_control/lqr_steer_control.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0)
35
39
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_steer_control/lqr_steer_control.py#L35-L39
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
89.542484
5
1
100
0
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v
623
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
differential_model
(v, yaw, u_1, u_2)
return dx, dy, d_yaw, dv
27
34
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L27-L34
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
90.987124
8
1
100
0
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
624
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
plot_figures
(plant_system, controller, iteration_num, dt)
390
479
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()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L390-L479
2
[]
0
[]
0
false
90.987124
90
1
100
0
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()
625
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
plot_car
(x, y, yaw, steer=0.0, truck_color="-k")
482
547
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, "*")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L482-L547
2
[]
0
[]
0
false
90.987124
66
1
100
0
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, "*")
626
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
animation
(plant, controller, dt)
550
580
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")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L550-L580
2
[ 0 ]
3.225806
[ 1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 16, 18, 21, 22, 23, 24, 25, 28, 30 ]
64.516129
false
90.987124
31
3
35.483871
0
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")
627
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
main
()
583
612
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)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L583-L612
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 26 ]
85.185185
[]
0
false
90.987124
30
3
100
0
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)
628
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
TwoWheeledSystem.__init__
(self, init_x, init_y, init_yaw, init_v)
39
47
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]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L39-L47
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
90.987124
9
1
100
0
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]
629
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
TwoWheeledSystem.update_state
(self, u_1, u_2, dt=0.01)
49
61
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)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L49-L61
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
90.987124
13
1
100
0
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)
630
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCSimulatorSystem.calc_predict_and_adjoint_state
(self, x, y, yaw, v, u_1s, u_2s, N, dt)
return x_s, y_s, yaw_s, v_s, lam_1s, lam_2s, lam_3s, lam_4s
66
74
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L66-L74
2
[ 0, 1, 2, 4, 5, 7, 8 ]
77.777778
[]
0
false
90.987124
9
1
100
0
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
631
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCSimulatorSystem._calc_predict_states
(self, x, y, yaw, v, u_1s, u_2s, N, dt)
return x_s, y_s, yaw_s, v_s
76
90
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L76-L90
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14 ]
93.333333
[]
0
false
90.987124
15
2
100
0
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
632
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCSimulatorSystem._calc_adjoint_states
(self, x_s, y_s, yaw_s, v_s, u_2s, N, dt)
return lam_1s, lam_2s, lam_3s, lam_4s
92
108
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L92-L108
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16 ]
88.235294
[]
0
false
90.987124
17
2
100
0
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
633
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCSimulatorSystem._predict_state_with_oylar
(x, y, yaw, v, u_1, u_2, dt)
return next_x_1, next_x_2, next_x_3, next_x_4
111
121
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L111-L121
2
[ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10 ]
90.909091
[]
0
false
90.987124
11
1
100
0
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
634
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCSimulatorSystem._adjoint_state_with_oylar
(yaw, v, lam_1, lam_2, lam_3, lam_4, u_2, dt)
return pre_lam_1, pre_lam_2, pre_lam_3, pre_lam_4
124
134
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L124-L134
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
90.987124
11
1
100
0
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
635
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCControllerCGMRES.__init__
(self)
186
214
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 = []
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L186-L214
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28 ]
100
[]
0
true
90.987124
29
1
100
0
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 = []
636
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCControllerCGMRES.calc_input
(self, x, y, yaw, v, time)
return self.u_1s, self.u_2s
216
368
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) # Gram–Schmidt 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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L216-L368
2
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 18, 19, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 45, 46, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 83, 84, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 136, 137, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152 ]
81.699346
[]
0
false
90.987124
153
5
100
0
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) # Gram–Schmidt 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
637
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/cgmres_nmpc/cgmres_nmpc.py
NMPCControllerCGMRES._calc_f
(v_s, lam_3s, lam_4s, u_1s, u_2s, dummy_u_1s, dummy_u_2s, raw_1s, raw_2s, N)
return np.array(F)
371
387
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)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/cgmres_nmpc/cgmres_nmpc.py#L371-L387
2
[ 0, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16 ]
88.235294
[]
0
false
90.987124
17
2
100
0
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)
638
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
update
(state, a, delta)
return state
39
51
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L39-L51
2
[ 0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 12 ]
84.615385
[ 3, 5 ]
15.384615
false
90.506329
13
3
84.615385
0
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
639
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
54
55
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L54-L55
2
[ 0, 1 ]
100
[]
0
true
90.506329
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
640
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
solve_dare
(A, B, Q, R)
return x_next
solve a discrete time_Algebraic Riccati equation (DARE)
solve a discrete time_Algebraic Riccati equation (DARE)
58
74
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L58-L74
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
90.506329
17
3
100
1
def solve_dare(A, B, Q, R): 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
641
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
dlqr
(A, B, Q, R)
return K, X, eig_result[0]
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
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
77
92
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]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L77-L92
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
90.506329
16
1
100
4
def dlqr(A, B, Q, R): # 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]
642
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
lqr_speed_steering_control
(state, cx, cy, cyaw, ck, pe, pth_e, sp, Q, R)
return delta, ind, e, th_e, accel
95
156
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L95-L156
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61 ]
100
[]
0
true
90.506329
62
1
100
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
643
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
calc_nearest_index
(state, cx, cy, cyaw)
return ind, mind
159
178
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L159-L178
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
90.506329
20
5
100
0
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
644
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
do_simulation
(cx, cy, cyaw, ck, speed_profile, goal)
return t, x, y, yaw, v
181
235
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L181-L235
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 53, 54 ]
76.363636
[ 41, 43, 45, 46, 47, 48, 49, 50, 52 ]
16.363636
false
90.506329
55
6
83.636364
0
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
645
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
calc_speed_profile
(cyaw, target_speed)
return speed_profile
238
265
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L238-L265
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 16, 17, 18, 21, 22, 23, 24, 25, 26, 27 ]
82.142857
[ 11, 14, 19 ]
10.714286
false
90.506329
28
7
89.285714
0
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
646
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
main
()
268
308
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(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()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L268-L308
2
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13 ]
76.470588
[]
0
false
90.506329
41
3
100
0
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(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()
647
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0)
32
36
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
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/lqr_speed_steer_control/lqr_speed_steer_control.py#L32-L36
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
90.506329
5
1
100
0
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v
648
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
proportional_control
(target, current)
return a
64
67
def proportional_control(target, current): a = Kp * (target - current) return a
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L64-L67
2
[ 0, 1, 2, 3 ]
100
[]
0
true
90.178571
4
1
100
0
def proportional_control(target, current): a = Kp * (target - current) return a
649
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
pure_pursuit_steer_control
(state, trajectory, pind)
return delta, ind
111
129
def pure_pursuit_steer_control(state, trajectory, pind): ind, Lf = trajectory.search_target_index(state) if pind >= ind: ind = pind if ind < len(trajectory.cx): tx = trajectory.cx[ind] ty = trajectory.cy[ind] else: # toward goal tx = trajectory.cx[-1] ty = trajectory.cy[-1] ind = len(trajectory.cx) - 1 alpha = math.atan2(ty - state.rear_y, tx - state.rear_x) - state.yaw delta = math.atan2(2.0 * WB * math.sin(alpha) / Lf, 1.0) return delta, ind
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L111-L129
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18 ]
78.947368
[ 10, 11, 12 ]
15.789474
false
90.178571
19
3
84.210526
0
def pure_pursuit_steer_control(state, trajectory, pind): ind, Lf = trajectory.search_target_index(state) if pind >= ind: ind = pind if ind < len(trajectory.cx): tx = trajectory.cx[ind] ty = trajectory.cy[ind] else: # toward goal tx = trajectory.cx[-1] ty = trajectory.cy[-1] ind = len(trajectory.cx) - 1 alpha = math.atan2(ty - state.rear_y, tx - state.rear_x) - state.yaw delta = math.atan2(2.0 * WB * math.sin(alpha) / Lf, 1.0) return delta, ind
650
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
plot_arrow
(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k")
Plot arrow
Plot arrow
132
143
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): """ 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)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L132-L143
2
[ 0, 1, 2, 3, 4 ]
41.666667
[ 5, 6, 7, 9, 11 ]
41.666667
false
90.178571
12
3
58.333333
1
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): 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)
651
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
main
()
146
210
def main(): # target course cx = np.arange(0, 50, 0.5) cy = [math.sin(ix / 5.0) * ix / 2.0 for ix in cx] target_speed = 10.0 / 3.6 # [m/s] T = 100.0 # max simulation time # initial state state = State(x=-0.0, y=-3.0, yaw=0.0, v=0.0) lastIndex = len(cx) - 1 time = 0.0 states = States() states.append(time, state) target_course = TargetCourse(cx, cy) target_ind, _ = target_course.search_target_index(state) while T >= time and lastIndex > target_ind: # Calc control input ai = proportional_control(target_speed, state.v) di, target_ind = pure_pursuit_steer_control( state, target_course, target_ind) state.update(ai, di) # Control vehicle time += dt states.append(time, state) 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]) plot_arrow(state.x, state.y, state.yaw) plt.plot(cx, cy, "-r", label="course") plt.plot(states.x, states.y, "-b", 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(state.v * 3.6)[:4]) plt.pause(0.001) # Test assert lastIndex >= target_ind, "Cannot goal" if show_animation: # pragma: no cover plt.cla() plt.plot(cx, cy, ".r", label="course") plt.plot(states.x, states.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(states.t, [iv * 3.6 for iv in states.v], "-r") plt.xlabel("Time[s]") plt.ylabel("Speed[km/h]") plt.grid(True) plt.show()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L146-L210
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 46, 47, 48 ]
84.615385
[]
0
false
90.178571
65
8
100
0
def main(): # target course cx = np.arange(0, 50, 0.5) cy = [math.sin(ix / 5.0) * ix / 2.0 for ix in cx] target_speed = 10.0 / 3.6 # [m/s] T = 100.0 # max simulation time # initial state state = State(x=-0.0, y=-3.0, yaw=0.0, v=0.0) lastIndex = len(cx) - 1 time = 0.0 states = States() states.append(time, state) target_course = TargetCourse(cx, cy) target_ind, _ = target_course.search_target_index(state) while T >= time and lastIndex > target_ind: # Calc control input ai = proportional_control(target_speed, state.v) di, target_ind = pure_pursuit_steer_control( state, target_course, target_ind) state.update(ai, di) # Control vehicle time += dt states.append(time, state) 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]) plot_arrow(state.x, state.y, state.yaw) plt.plot(cx, cy, "-r", label="course") plt.plot(states.x, states.y, "-b", 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(state.v * 3.6)[:4]) plt.pause(0.001) # Test assert lastIndex >= target_ind, "Cannot goal" if show_animation: # pragma: no cover plt.cla() plt.plot(cx, cy, ".r", label="course") plt.plot(states.x, states.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(states.t, [iv * 3.6 for iv in states.v], "-r") plt.xlabel("Time[s]") plt.ylabel("Speed[km/h]") plt.grid(True) plt.show()
652
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
State.__init__
(self, x=0.0, y=0.0, yaw=0.0, v=0.0)
25
31
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v self.rear_x = self.x - ((WB / 2) * math.cos(self.yaw)) self.rear_y = self.y - ((WB / 2) * math.sin(self.yaw))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L25-L31
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
90.178571
7
1
100
0
def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0): self.x = x self.y = y self.yaw = yaw self.v = v self.rear_x = self.x - ((WB / 2) * math.cos(self.yaw)) self.rear_y = self.y - ((WB / 2) * math.sin(self.yaw))
653
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
State.update
(self, a, delta)
33
39
def update(self, a, delta): self.x += self.v * math.cos(self.yaw) * dt self.y += self.v * math.sin(self.yaw) * dt self.yaw += self.v / WB * math.tan(delta) * dt self.v += a * dt self.rear_x = self.x - ((WB / 2) * math.cos(self.yaw)) self.rear_y = self.y - ((WB / 2) * math.sin(self.yaw))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L33-L39
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
90.178571
7
1
100
0
def update(self, a, delta): self.x += self.v * math.cos(self.yaw) * dt self.y += self.v * math.sin(self.yaw) * dt self.yaw += self.v / WB * math.tan(delta) * dt self.v += a * dt self.rear_x = self.x - ((WB / 2) * math.cos(self.yaw)) self.rear_y = self.y - ((WB / 2) * math.sin(self.yaw))
654
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
State.calc_distance
(self, point_x, point_y)
return math.hypot(dx, dy)
41
44
def calc_distance(self, point_x, point_y): dx = self.rear_x - point_x dy = self.rear_y - point_y return math.hypot(dx, dy)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L41-L44
2
[ 0, 1, 2, 3 ]
100
[]
0
true
90.178571
4
1
100
0
def calc_distance(self, point_x, point_y): dx = self.rear_x - point_x dy = self.rear_y - point_y return math.hypot(dx, dy)
655
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
States.__init__
(self)
49
54
def __init__(self): self.x = [] self.y = [] self.yaw = [] self.v = [] self.t = []
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L49-L54
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
90.178571
6
1
100
0
def __init__(self): self.x = [] self.y = [] self.yaw = [] self.v = [] self.t = []
656
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
States.append
(self, t, state)
56
61
def append(self, t, state): self.x.append(state.x) self.y.append(state.y) self.yaw.append(state.yaw) self.v.append(state.v) self.t.append(t)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L56-L61
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
90.178571
6
1
100
0
def append(self, t, state): self.x.append(state.x) self.y.append(state.y) self.yaw.append(state.yaw) self.v.append(state.v) self.t.append(t)
657
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
TargetCourse.__init__
(self, cx, cy)
72
75
def __init__(self, cx, cy): self.cx = cx self.cy = cy self.old_nearest_point_index = None
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L72-L75
2
[ 0, 1, 2, 3 ]
100
[]
0
true
90.178571
4
1
100
0
def __init__(self, cx, cy): self.cx = cx self.cy = cy self.old_nearest_point_index = None
658
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/pure_pursuit/pure_pursuit.py
TargetCourse.search_target_index
(self, state)
return ind, Lf
77
108
def search_target_index(self, state): # To speed up nearest point search, doing it at only first time. if self.old_nearest_point_index is None: # search nearest point index dx = [state.rear_x - icx for icx in self.cx] dy = [state.rear_y - icy for icy in self.cy] d = np.hypot(dx, dy) ind = np.argmin(d) self.old_nearest_point_index = ind else: ind = self.old_nearest_point_index distance_this_index = state.calc_distance(self.cx[ind], self.cy[ind]) while True: distance_next_index = state.calc_distance(self.cx[ind + 1], self.cy[ind + 1]) if distance_this_index < distance_next_index: break ind = ind + 1 if (ind + 1) < len(self.cx) else ind distance_this_index = distance_next_index self.old_nearest_point_index = ind Lf = k * state.v + Lfc # update look ahead distance # search look ahead target point index while Lf > state.calc_distance(self.cx[ind], self.cy[ind]): if (ind + 1) >= len(self.cx): break # not exceed goal ind += 1 return ind, Lf
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/pure_pursuit/pure_pursuit.py#L77-L108
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31 ]
87.5
[ 28 ]
3.125
false
90.178571
32
8
96.875
0
def search_target_index(self, state): # To speed up nearest point search, doing it at only first time. if self.old_nearest_point_index is None: # search nearest point index dx = [state.rear_x - icx for icx in self.cx] dy = [state.rear_y - icy for icy in self.cy] d = np.hypot(dx, dy) ind = np.argmin(d) self.old_nearest_point_index = ind else: ind = self.old_nearest_point_index distance_this_index = state.calc_distance(self.cx[ind], self.cy[ind]) while True: distance_next_index = state.calc_distance(self.cx[ind + 1], self.cy[ind + 1]) if distance_this_index < distance_next_index: break ind = ind + 1 if (ind + 1) < len(self.cx) else ind distance_this_index = distance_next_index self.old_nearest_point_index = ind Lf = k * state.v + Lfc # update look ahead distance # search look ahead target point index while Lf > state.calc_distance(self.cx[ind], self.cy[ind]): if (ind + 1) >= len(self.cx): break # not exceed goal ind += 1 return ind, Lf
659
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
PathTracking/rear_wheel_feedback/rear_wheel_feedback.py
pid_control
(target, current)
return a
94
96
def pid_control(target, current): a = Kp * (target - current) return a
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/PathTracking/rear_wheel_feedback/rear_wheel_feedback.py#L94-L96
2
[ 0, 1, 2 ]
100
[]
0
true
92.307692
3
1
100
0
def pid_control(target, current): a = Kp * (target - current) return a
660