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
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
quad_sim
(x_c, y_c, z_c)
Calculates the necessary thrust and torques for the quadrotor to follow the trajectory described by the sets of coefficients x_c, y_c, and z_c.
Calculates the necessary thrust and torques for the quadrotor to follow the trajectory described by the sets of coefficients x_c, y_c, and z_c.
37
123
def quad_sim(x_c, y_c, z_c): """ Calculates the necessary thrust and torques for the quadrotor to follow the trajectory described by the sets of coefficients x_c, y_c, and z_c. """ x_pos = -5 y_pos = -5 z_pos = 5 x_vel = 0 y_vel = 0 z_vel = 0 x_acc = 0 y_acc = 0 z_acc = 0 roll = 0 pitch = 0 yaw = 0 roll_vel = 0 pitch_vel = 0 yaw_vel = 0 des_yaw = 0 dt = 0.1 t = 0 q = Quadrotor(x=x_pos, y=y_pos, z=z_pos, roll=roll, pitch=pitch, yaw=yaw, size=1, show_animation=show_animation) i = 0 n_run = 8 irun = 0 while True: while t <= T: # des_x_pos = calculate_position(x_c[i], t) # des_y_pos = calculate_position(y_c[i], t) des_z_pos = calculate_position(z_c[i], t) # des_x_vel = calculate_velocity(x_c[i], t) # des_y_vel = calculate_velocity(y_c[i], t) des_z_vel = calculate_velocity(z_c[i], t) des_x_acc = calculate_acceleration(x_c[i], t) des_y_acc = calculate_acceleration(y_c[i], t) des_z_acc = calculate_acceleration(z_c[i], t) thrust = m * (g + des_z_acc + Kp_z * (des_z_pos - z_pos) + Kd_z * (des_z_vel - z_vel)) roll_torque = Kp_roll * \ (((des_x_acc * sin(des_yaw) - des_y_acc * cos(des_yaw)) / g) - roll) pitch_torque = Kp_pitch * \ (((des_x_acc * cos(des_yaw) - des_y_acc * sin(des_yaw)) / g) - pitch) yaw_torque = Kp_yaw * (des_yaw - yaw) roll_vel += roll_torque * dt / Ixx pitch_vel += pitch_torque * dt / Iyy yaw_vel += yaw_torque * dt / Izz roll += roll_vel * dt pitch += pitch_vel * dt yaw += yaw_vel * dt R = rotation_matrix(roll, pitch, yaw) acc = (np.matmul(R, np.array( [0, 0, thrust.item()]).T) - np.array([0, 0, m * g]).T) / m x_acc = acc[0] y_acc = acc[1] z_acc = acc[2] x_vel += x_acc * dt y_vel += y_acc * dt z_vel += z_acc * dt x_pos += x_vel * dt y_pos += y_vel * dt z_pos += z_vel * dt q.update_pose(x_pos, y_pos, z_pos, roll, pitch, yaw) t += dt t = 0 i = (i + 1) % 4 irun += 1 if irun >= n_run: break print("Done")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L37-L123
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 ]
100
[]
0
true
99.019608
87
4
100
3
def quad_sim(x_c, y_c, z_c): x_pos = -5 y_pos = -5 z_pos = 5 x_vel = 0 y_vel = 0 z_vel = 0 x_acc = 0 y_acc = 0 z_acc = 0 roll = 0 pitch = 0 yaw = 0 roll_vel = 0 pitch_vel = 0 yaw_vel = 0 des_yaw = 0 dt = 0.1 t = 0 q = Quadrotor(x=x_pos, y=y_pos, z=z_pos, roll=roll, pitch=pitch, yaw=yaw, size=1, show_animation=show_animation) i = 0 n_run = 8 irun = 0 while True: while t <= T: # des_x_pos = calculate_position(x_c[i], t) # des_y_pos = calculate_position(y_c[i], t) des_z_pos = calculate_position(z_c[i], t) # des_x_vel = calculate_velocity(x_c[i], t) # des_y_vel = calculate_velocity(y_c[i], t) des_z_vel = calculate_velocity(z_c[i], t) des_x_acc = calculate_acceleration(x_c[i], t) des_y_acc = calculate_acceleration(y_c[i], t) des_z_acc = calculate_acceleration(z_c[i], t) thrust = m * (g + des_z_acc + Kp_z * (des_z_pos - z_pos) + Kd_z * (des_z_vel - z_vel)) roll_torque = Kp_roll * \ (((des_x_acc * sin(des_yaw) - des_y_acc * cos(des_yaw)) / g) - roll) pitch_torque = Kp_pitch * \ (((des_x_acc * cos(des_yaw) - des_y_acc * sin(des_yaw)) / g) - pitch) yaw_torque = Kp_yaw * (des_yaw - yaw) roll_vel += roll_torque * dt / Ixx pitch_vel += pitch_torque * dt / Iyy yaw_vel += yaw_torque * dt / Izz roll += roll_vel * dt pitch += pitch_vel * dt yaw += yaw_vel * dt R = rotation_matrix(roll, pitch, yaw) acc = (np.matmul(R, np.array( [0, 0, thrust.item()]).T) - np.array([0, 0, m * g]).T) / m x_acc = acc[0] y_acc = acc[1] z_acc = acc[2] x_vel += x_acc * dt y_vel += y_acc * dt z_vel += z_acc * dt x_pos += x_vel * dt y_pos += y_vel * dt z_pos += z_vel * dt q.update_pose(x_pos, y_pos, z_pos, roll, pitch, yaw) t += dt t = 0 i = (i + 1) % 4 irun += 1 if irun >= n_run: break print("Done")
1,301
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
calculate_position
(c, t)
return c[0] * t**5 + c[1] * t**4 + c[2] * t**3 + c[3] * t**2 + c[4] * t + c[5]
Calculates a position given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the position Returns Position
Calculates a position given a set of quintic coefficients and a time.
126
138
def calculate_position(c, t): """ Calculates a position given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the position Returns Position """ return c[0] * t**5 + c[1] * t**4 + c[2] * t**3 + c[3] * t**2 + c[4] * t + c[5]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L126-L138
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
99.019608
13
1
100
9
def calculate_position(c, t): return c[0] * t**5 + c[1] * t**4 + c[2] * t**3 + c[3] * t**2 + c[4] * t + c[5]
1,302
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
calculate_velocity
(c, t)
return 5 * c[0] * t**4 + 4 * c[1] * t**3 + 3 * c[2] * t**2 + 2 * c[3] * t + c[4]
Calculates a velocity given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the velocity Returns Velocity
Calculates a velocity given a set of quintic coefficients and a time.
141
153
def calculate_velocity(c, t): """ Calculates a velocity given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the velocity Returns Velocity """ return 5 * c[0] * t**4 + 4 * c[1] * t**3 + 3 * c[2] * t**2 + 2 * c[3] * t + c[4]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L141-L153
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
99.019608
13
1
100
9
def calculate_velocity(c, t): return 5 * c[0] * t**4 + 4 * c[1] * t**3 + 3 * c[2] * t**2 + 2 * c[3] * t + c[4]
1,303
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
calculate_acceleration
(c, t)
return 20 * c[0] * t**3 + 12 * c[1] * t**2 + 6 * c[2] * t + 2 * c[3]
Calculates an acceleration given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the acceleration Returns Acceleration
Calculates an acceleration given a set of quintic coefficients and a time.
156
168
def calculate_acceleration(c, t): """ Calculates an acceleration given a set of quintic coefficients and a time. Args c: List of coefficients generated by a quintic polynomial trajectory generator. t: Time at which to calculate the acceleration Returns Acceleration """ return 20 * c[0] * t**3 + 12 * c[1] * t**2 + 6 * c[2] * t + 2 * c[3]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L156-L168
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
99.019608
13
1
100
9
def calculate_acceleration(c, t): return 20 * c[0] * t**3 + 12 * c[1] * t**2 + 6 * c[2] * t + 2 * c[3]
1,304
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
rotation_matrix
(roll, pitch, yaw)
return np.array( [[cos(yaw) * cos(pitch), -sin(yaw) * cos(roll) + cos(yaw) * sin(pitch) * sin(roll), sin(yaw) * sin(roll) + cos(yaw) * sin(pitch) * cos(roll)], [sin(yaw) * cos(pitch), cos(yaw) * cos(roll) + sin(yaw) * sin(pitch) * sin(roll), -cos(yaw) * sin(roll) + sin(yaw) * sin(pitch) * cos(roll)], [-sin(pitch), cos(pitch) * sin(roll), cos(pitch) * cos(yaw)] ])
Calculates the ZYX rotation matrix. Args Roll: Angular position about the x-axis in radians. Pitch: Angular position about the y-axis in radians. Yaw: Angular position about the z-axis in radians. Returns 3x3 rotation matrix as NumPy array
Calculates the ZYX rotation matrix.
171
188
def rotation_matrix(roll, pitch, yaw): """ Calculates the ZYX rotation matrix. Args Roll: Angular position about the x-axis in radians. Pitch: Angular position about the y-axis in radians. Yaw: Angular position about the z-axis in radians. Returns 3x3 rotation matrix as NumPy array """ return np.array( [[cos(yaw) * cos(pitch), -sin(yaw) * cos(roll) + cos(yaw) * sin(pitch) * sin(roll), sin(yaw) * sin(roll) + cos(yaw) * sin(pitch) * cos(roll)], [sin(yaw) * cos(pitch), cos(yaw) * cos(roll) + sin(yaw) * sin(pitch) * sin(roll), -cos(yaw) * sin(roll) + sin(yaw) * sin(pitch) * cos(roll)], [-sin(pitch), cos(pitch) * sin(roll), cos(pitch) * cos(yaw)] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L171-L188
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
99.019608
18
1
100
9
def rotation_matrix(roll, pitch, yaw): return np.array( [[cos(yaw) * cos(pitch), -sin(yaw) * cos(roll) + cos(yaw) * sin(pitch) * sin(roll), sin(yaw) * sin(roll) + cos(yaw) * sin(pitch) * cos(roll)], [sin(yaw) * cos(pitch), cos(yaw) * cos(roll) + sin(yaw) * sin(pitch) * sin(roll), -cos(yaw) * sin(roll) + sin(yaw) * sin(pitch) * cos(roll)], [-sin(pitch), cos(pitch) * sin(roll), cos(pitch) * cos(yaw)] ])
1,305
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py
main
()
Calculates the x, y, z coefficients for the four segments of the trajectory
Calculates the x, y, z coefficients for the four segments of the trajectory
191
208
def main(): """ Calculates the x, y, z coefficients for the four segments of the trajectory """ x_coeffs = [[], [], [], []] y_coeffs = [[], [], [], []] z_coeffs = [[], [], [], []] waypoints = [[-5, -5, 5], [5, -5, 5], [5, 5, 5], [-5, 5, 5]] for i in range(4): traj = TrajectoryGenerator(waypoints[i], waypoints[(i + 1) % 4], T) traj.solve() x_coeffs[i] = traj.x_c y_coeffs[i] = traj.y_c z_coeffs[i] = traj.z_c quad_sim(x_coeffs, y_coeffs, z_coeffs)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/drone_3d_trajectory_following/drone_3d_trajectory_following.py#L191-L208
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
99.019608
18
2
100
2
def main(): x_coeffs = [[], [], [], []] y_coeffs = [[], [], [], []] z_coeffs = [[], [], [], []] waypoints = [[-5, -5, 5], [5, -5, 5], [5, 5, 5], [-5, 5, 5]] for i in range(4): traj = TrajectoryGenerator(waypoints[i], waypoints[(i + 1) % 4], T) traj.solve() x_coeffs[i] = traj.x_c y_coeffs[i] = traj.y_c z_coeffs[i] = traj.z_c quad_sim(x_coeffs, y_coeffs, z_coeffs)
1,306
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
axis3d_equal
(X, Y, Z, ax)
554
566
def axis3d_equal(X, Y, Z, ax): max_range = np.array([X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max() Xb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][0].flatten() + 0.5 * (X.max() + X.min()) Yb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][1].flatten() + 0.5 * (Y.max() + Y.min()) Zb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][2].flatten() + 0.5 * (Z.max() + Z.min()) # Comment or uncomment following both lines to test the fake bounding box: for xb, yb, zb in zip(Xb, Yb, Zb): ax.plot([xb], [yb], [zb], 'w')
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L554-L566
2
[ 0, 1 ]
15.384615
[ 2, 4, 6, 8, 11, 12 ]
46.153846
false
94.573643
13
2
53.846154
0
def axis3d_equal(X, Y, Z, ax): max_range = np.array([X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min()]).max() Xb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][0].flatten() + 0.5 * (X.max() + X.min()) Yb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][1].flatten() + 0.5 * (Y.max() + Y.min()) Zb = 0.5 * max_range * np.mgrid[-1:2:2, -1:2:2, - 1:2:2][2].flatten() + 0.5 * (Z.max() + Z.min()) # Comment or uncomment following both lines to test the fake bounding box: for xb, yb, zb in zip(Xb, Yb, Zb): ax.plot([xb], [yb], [zb], 'w')
1,307
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
plot_animation
(X, U)
569
609
def plot_animation(X, U): # pragma: no cover fig = plt.figure() ax = fig.gca(projection='3d') # for stopping simulation with the esc key. fig.canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) for k in range(K): plt.cla() ax.plot(X[2, :], X[3, :], X[1, :]) # trajectory ax.scatter3D([0.0], [0.0], [0.0], c="r", marker="x") # target landing point axis3d_equal(X[2, :], X[3, :], X[1, :], ax) rx, ry, rz = X[1:4, k] # vx, vy, vz = X[4:7, k] qw, qx, qy, qz = X[7:11, k] CBI = np.array([ [1 - 2 * (qy ** 2 + qz ** 2), 2 * (qx * qy + qw * qz), 2 * (qx * qz - qw * qy)], [2 * (qx * qy - qw * qz), 1 - 2 * (qx ** 2 + qz ** 2), 2 * (qy * qz + qw * qx)], [2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx ** 2 + qy ** 2)] ]) Fx, Fy, Fz = np.dot(np.transpose(CBI), U[:, k]) dx, dy, dz = np.dot(np.transpose(CBI), np.array([1., 0., 0.])) # attitude vector ax.quiver(ry, rz, rx, dy, dz, dx, length=0.5, linewidth=3.0, arrow_length_ratio=0.0, color='black') # thrust vector ax.quiver(ry, rz, rx, -Fy, -Fz, -Fx, length=0.1, arrow_length_ratio=0.0, color='red') ax.set_title("Rocket powered landing") plt.pause(0.5)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L569-L609
2
[]
0
[]
0
false
94.573643
41
2
100
0
def plot_animation(X, U): # pragma: no cover fig = plt.figure() ax = fig.gca(projection='3d') # for stopping simulation with the esc key. fig.canvas.mpl_connect('key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) for k in range(K): plt.cla() ax.plot(X[2, :], X[3, :], X[1, :]) # trajectory ax.scatter3D([0.0], [0.0], [0.0], c="r", marker="x") # target landing point axis3d_equal(X[2, :], X[3, :], X[1, :], ax) rx, ry, rz = X[1:4, k] # vx, vy, vz = X[4:7, k] qw, qx, qy, qz = X[7:11, k] CBI = np.array([ [1 - 2 * (qy ** 2 + qz ** 2), 2 * (qx * qy + qw * qz), 2 * (qx * qz - qw * qy)], [2 * (qx * qy - qw * qz), 1 - 2 * (qx ** 2 + qz ** 2), 2 * (qy * qz + qw * qx)], [2 * (qx * qz + qw * qy), 2 * (qy * qz - qw * qx), 1 - 2 * (qx ** 2 + qy ** 2)] ]) Fx, Fy, Fz = np.dot(np.transpose(CBI), U[:, k]) dx, dy, dz = np.dot(np.transpose(CBI), np.array([1., 0., 0.])) # attitude vector ax.quiver(ry, rz, rx, dy, dz, dx, length=0.5, linewidth=3.0, arrow_length_ratio=0.0, color='black') # thrust vector ax.quiver(ry, rz, rx, -Fy, -Fz, -Fx, length=0.1, arrow_length_ratio=0.0, color='red') ax.set_title("Rocket powered landing") plt.pause(0.5)
1,308
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
main
(rng=None)
612
668
def main(rng=None): print("start!!") m = Rocket_Model_6DoF(rng) # state and input list X = np.empty(shape=[m.n_x, K]) U = np.empty(shape=[m.n_u, K]) # INITIALIZATION sigma = m.t_f_guess X, U = m.initialize_trajectory(X, U) integrator = Integrator(m, K) problem = SCProblem(m, K) converged = False w_delta = W_DELTA for it in range(iterations): t0_it = time() print('-' * 18 + f' Iteration {str(it + 1).zfill(2)} ' + '-' * 18) A_bar, B_bar, C_bar, S_bar, z_bar = integrator.calculate_discretization( X, U, sigma) problem.set_parameters(A_bar=A_bar, B_bar=B_bar, C_bar=C_bar, S_bar=S_bar, z_bar=z_bar, X_last=X, U_last=U, sigma_last=sigma, weight_sigma=W_SIGMA, weight_nu=W_NU, weight_delta=w_delta, weight_delta_sigma=W_DELTA_SIGMA) problem.solve() X = problem.get_variable('X') U = problem.get_variable('U') sigma = problem.get_variable('sigma') delta_norm = problem.get_variable('delta_norm') sigma_norm = problem.get_variable('sigma_norm') nu_norm = np.linalg.norm(problem.get_variable('nu'), np.inf) print('delta_norm', delta_norm) print('sigma_norm', sigma_norm) print('nu_norm', nu_norm) if delta_norm < 1e-3 and sigma_norm < 1e-3 and nu_norm < 1e-7: converged = True w_delta *= 1.5 print('Time for iteration', time() - t0_it, 's') if converged: print(f'Converged after {it + 1} iterations.') break if show_animation: # pragma: no cover plot_animation(X, U) print("done!!")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L612-L668
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 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, 55, 56 ]
92.727273
[]
0
false
94.573643
57
7
100
0
def main(rng=None): print("start!!") m = Rocket_Model_6DoF(rng) # state and input list X = np.empty(shape=[m.n_x, K]) U = np.empty(shape=[m.n_u, K]) # INITIALIZATION sigma = m.t_f_guess X, U = m.initialize_trajectory(X, U) integrator = Integrator(m, K) problem = SCProblem(m, K) converged = False w_delta = W_DELTA for it in range(iterations): t0_it = time() print('-' * 18 + f' Iteration {str(it + 1).zfill(2)} ' + '-' * 18) A_bar, B_bar, C_bar, S_bar, z_bar = integrator.calculate_discretization( X, U, sigma) problem.set_parameters(A_bar=A_bar, B_bar=B_bar, C_bar=C_bar, S_bar=S_bar, z_bar=z_bar, X_last=X, U_last=U, sigma_last=sigma, weight_sigma=W_SIGMA, weight_nu=W_NU, weight_delta=w_delta, weight_delta_sigma=W_DELTA_SIGMA) problem.solve() X = problem.get_variable('X') U = problem.get_variable('U') sigma = problem.get_variable('sigma') delta_norm = problem.get_variable('delta_norm') sigma_norm = problem.get_variable('sigma_norm') nu_norm = np.linalg.norm(problem.get_variable('nu'), np.inf) print('delta_norm', delta_norm) print('sigma_norm', sigma_norm) print('nu_norm', nu_norm) if delta_norm < 1e-3 and sigma_norm < 1e-3 and nu_norm < 1e-7: converged = True w_delta *= 1.5 print('Time for iteration', time() - t0_it, 's') if converged: print(f'Converged after {it + 1} iterations.') break if show_animation: # pragma: no cover plot_animation(X, U) print("done!!")
1,309
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.__init__
(self, rng)
A large r_scale for a small scale problem will ead to numerical problems as parameters become excessively small and (it seems) precision is lost in the dynamics.
A large r_scale for a small scale problem will ead to numerical problems as parameters become excessively small and (it seems) precision is lost in the dynamics.
46
103
def __init__(self, rng): """ A large r_scale for a small scale problem will ead to numerical problems as parameters become excessively small and (it seems) precision is lost in the dynamics. """ self.n_x = 14 self.n_u = 3 # Mass self.m_wet = 3.0 # 30000 kg self.m_dry = 2.2 # 22000 kg # Flight time guess self.t_f_guess = 10.0 # 10 s # State constraints self.r_I_final = np.array((0., 0., 0.)) self.v_I_final = np.array((-1e-1, 0., 0.)) self.q_B_I_final = self.euler_to_quat((0, 0, 0)) self.w_B_final = np.deg2rad(np.array((0., 0., 0.))) self.w_B_max = np.deg2rad(60) # Angles max_gimbal = 20 max_angle = 90 glidelslope_angle = 20 self.tan_delta_max = np.tan(np.deg2rad(max_gimbal)) self.cos_theta_max = np.cos(np.deg2rad(max_angle)) self.tan_gamma_gs = np.tan(np.deg2rad(glidelslope_angle)) # Thrust limits self.T_max = 5.0 self.T_min = 0.3 # Angular moment of inertia self.J_B = 1e-2 * np.diag([1., 1., 1.]) # Gravity self.g_I = np.array((-1, 0., 0.)) # Fuel consumption self.alpha_m = 0.01 # Vector from thrust point to CoM self.r_T_B = np.array([-1e-2, 0., 0.]) self.set_random_initial_state(rng) self.x_init = np.concatenate( ((self.m_wet,), self.r_I_init, self.v_I_init, self.q_B_I_init, self.w_B_init)) self.x_final = np.concatenate( ((self.m_dry,), self.r_I_final, self.v_I_final, self.q_B_I_final, self.w_B_final)) self.r_scale = np.linalg.norm(self.r_I_init) self.m_scale = self.m_wet
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L46-L103
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 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
94.573643
58
1
100
3
def __init__(self, rng): self.n_x = 14 self.n_u = 3 # Mass self.m_wet = 3.0 # 30000 kg self.m_dry = 2.2 # 22000 kg # Flight time guess self.t_f_guess = 10.0 # 10 s # State constraints self.r_I_final = np.array((0., 0., 0.)) self.v_I_final = np.array((-1e-1, 0., 0.)) self.q_B_I_final = self.euler_to_quat((0, 0, 0)) self.w_B_final = np.deg2rad(np.array((0., 0., 0.))) self.w_B_max = np.deg2rad(60) # Angles max_gimbal = 20 max_angle = 90 glidelslope_angle = 20 self.tan_delta_max = np.tan(np.deg2rad(max_gimbal)) self.cos_theta_max = np.cos(np.deg2rad(max_angle)) self.tan_gamma_gs = np.tan(np.deg2rad(glidelslope_angle)) # Thrust limits self.T_max = 5.0 self.T_min = 0.3 # Angular moment of inertia self.J_B = 1e-2 * np.diag([1., 1., 1.]) # Gravity self.g_I = np.array((-1, 0., 0.)) # Fuel consumption self.alpha_m = 0.01 # Vector from thrust point to CoM self.r_T_B = np.array([-1e-2, 0., 0.]) self.set_random_initial_state(rng) self.x_init = np.concatenate( ((self.m_wet,), self.r_I_init, self.v_I_init, self.q_B_I_init, self.w_B_init)) self.x_final = np.concatenate( ((self.m_dry,), self.r_I_final, self.v_I_final, self.q_B_I_final, self.w_B_final)) self.r_scale = np.linalg.norm(self.r_I_init) self.m_scale = self.m_wet
1,310
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.set_random_initial_state
(self, rng)
105
123
def set_random_initial_state(self, rng): if rng is None: rng = np.random.default_rng() self.r_I_init = np.array((0., 0., 0.)) self.r_I_init[0] = rng.uniform(3, 4) self.r_I_init[1:3] = rng.uniform(-2, 2, size=2) self.v_I_init = np.array((0., 0., 0.)) self.v_I_init[0] = rng.uniform(-1, -0.5) self.v_I_init[1:3] = rng.uniform(-0.5, -0.2, size=2) * self.r_I_init[1:3] self.q_B_I_init = self.euler_to_quat((0, rng.uniform(-30, 30), rng.uniform(-30, 30))) self.w_B_init = np.deg2rad((0, rng.uniform(-20, 20), rng.uniform(-20, 20)))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L105-L123
2
[ 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 16 ]
68.421053
[ 2 ]
5.263158
false
94.573643
19
2
94.736842
0
def set_random_initial_state(self, rng): if rng is None: rng = np.random.default_rng() self.r_I_init = np.array((0., 0., 0.)) self.r_I_init[0] = rng.uniform(3, 4) self.r_I_init[1:3] = rng.uniform(-2, 2, size=2) self.v_I_init = np.array((0., 0., 0.)) self.v_I_init[0] = rng.uniform(-1, -0.5) self.v_I_init[1:3] = rng.uniform(-0.5, -0.2, size=2) * self.r_I_init[1:3] self.q_B_I_init = self.euler_to_quat((0, rng.uniform(-30, 30), rng.uniform(-30, 30))) self.w_B_init = np.deg2rad((0, rng.uniform(-20, 20), rng.uniform(-20, 20)))
1,311
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.f_func
(self, x, u)
return np.array([ [-0.01 * np.sqrt(ux**2 + uy**2 + uz**2)], [vx], [vy], [vz], [(-1.0 * m - ux * (2 * q2**2 + 2 * q3**2 - 1) - 2 * uy * (q0 * q3 - q1 * q2) + 2 * uz * (q0 * q2 + q1 * q3)) / m], [(2 * ux * (q0 * q3 + q1 * q2) - uy * (2 * q1**2 + 2 * q3**2 - 1) - 2 * uz * (q0 * q1 - q2 * q3)) / m], [(-2 * ux * (q0 * q2 - q1 * q3) + 2 * uy * (q0 * q1 + q2 * q3) - uz * (2 * q1**2 + 2 * q2**2 - 1)) / m], [-0.5 * q1 * wx - 0.5 * q2 * wy - 0.5 * q3 * wz], [0.5 * q0 * wx + 0.5 * q2 * wz - 0.5 * q3 * wy], [0.5 * q0 * wy - 0.5 * q1 * wz + 0.5 * q3 * wx], [0.5 * q0 * wz + 0.5 * q1 * wy - 0.5 * q2 * wx], [0], [1.0 * uz], [-1.0 * uy] ])
125
148
def f_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [-0.01 * np.sqrt(ux**2 + uy**2 + uz**2)], [vx], [vy], [vz], [(-1.0 * m - ux * (2 * q2**2 + 2 * q3**2 - 1) - 2 * uy * (q0 * q3 - q1 * q2) + 2 * uz * (q0 * q2 + q1 * q3)) / m], [(2 * ux * (q0 * q3 + q1 * q2) - uy * (2 * q1**2 + 2 * q3**2 - 1) - 2 * uz * (q0 * q1 - q2 * q3)) / m], [(-2 * ux * (q0 * q2 - q1 * q3) + 2 * uy * (q0 * q1 + q2 * q3) - uz * (2 * q1**2 + 2 * q2**2 - 1)) / m], [-0.5 * q1 * wx - 0.5 * q2 * wy - 0.5 * q3 * wz], [0.5 * q0 * wx + 0.5 * q2 * wz - 0.5 * q3 * wy], [0.5 * q0 * wy - 0.5 * q1 * wz + 0.5 * q3 * wx], [0.5 * q0 * wz + 0.5 * q1 * wy - 0.5 * q2 * wx], [0], [1.0 * uz], [-1.0 * uy] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L125-L148
2
[ 0, 1, 3, 4, 5 ]
20.833333
[]
0
false
94.573643
24
1
100
0
def f_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [-0.01 * np.sqrt(ux**2 + uy**2 + uz**2)], [vx], [vy], [vz], [(-1.0 * m - ux * (2 * q2**2 + 2 * q3**2 - 1) - 2 * uy * (q0 * q3 - q1 * q2) + 2 * uz * (q0 * q2 + q1 * q3)) / m], [(2 * ux * (q0 * q3 + q1 * q2) - uy * (2 * q1**2 + 2 * q3**2 - 1) - 2 * uz * (q0 * q1 - q2 * q3)) / m], [(-2 * ux * (q0 * q2 - q1 * q3) + 2 * uy * (q0 * q1 + q2 * q3) - uz * (2 * q1**2 + 2 * q2**2 - 1)) / m], [-0.5 * q1 * wx - 0.5 * q2 * wy - 0.5 * q3 * wz], [0.5 * q0 * wx + 0.5 * q2 * wz - 0.5 * q3 * wy], [0.5 * q0 * wy - 0.5 * q1 * wz + 0.5 * q3 * wx], [0.5 * q0 * wz + 0.5 * q1 * wy - 0.5 * q2 * wx], [0], [1.0 * uz], [-1.0 * uy] ])
1,312
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.A_func
(self, x, u)
return np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [(ux * (2 * q2**2 + 2 * q3**2 - 1) + 2 * uy * (q0 * q3 - q1 * q2) - 2 * uz * (q0 * q2 + q1 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q2 * uz - q3 * uy) / m, 2 * (q2 * uy + q3 * uz) / m, 2 * (q0 * uz + q1 * uy - 2 * q2 * ux) / m, 2 * (-q0 * uy + q1 * uz - 2 * q3 * ux) / m, 0, 0, 0], [(-2 * ux * (q0 * q3 + q1 * q2) + uy * (2 * q1**2 + 2 * q3**2 - 1) + 2 * uz * (q0 * q1 - q2 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (-q1 * uz + q3 * ux) / m, 2 * (-q0 * uz - 2 * q1 * uy + q2 * ux) / m, 2 * (q1 * ux + q3 * uz) / m, 2 * (q0 * ux + q2 * uz - 2 * q3 * uy) / m, 0, 0, 0], [(2 * ux * (q0 * q2 - q1 * q3) - 2 * uy * (q0 * q1 + q2 * q3) + uz * (2 * q1**2 + 2 * q2**2 - 1)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q1 * uy - q2 * ux) / m, 2 * (q0 * uy - 2 * q1 * uz + q3 * ux) / m, 2 * (-q0 * ux - 2 * q2 * uz + q3 * uy) / m, 2 * (q1 * ux + q2 * uy) / m, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -0.5 * wx, -0.5 * wy, - 0.5 * wz, -0.5 * q1, -0.5 * q2, -0.5 * q3], [0, 0, 0, 0, 0, 0, 0, 0.5 * wx, 0, 0.5 * wz, - 0.5 * wy, 0.5 * q0, -0.5 * q3, 0.5 * q2], [0, 0, 0, 0, 0, 0, 0, 0.5 * wy, -0.5 * wz, 0, 0.5 * wx, 0.5 * q3, 0.5 * q0, -0.5 * q1], [0, 0, 0, 0, 0, 0, 0, 0.5 * wz, 0.5 * wy, - 0.5 * wx, 0, -0.5 * q2, 0.5 * q1, 0.5 * q0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
150
176
def A_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [(ux * (2 * q2**2 + 2 * q3**2 - 1) + 2 * uy * (q0 * q3 - q1 * q2) - 2 * uz * (q0 * q2 + q1 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q2 * uz - q3 * uy) / m, 2 * (q2 * uy + q3 * uz) / m, 2 * (q0 * uz + q1 * uy - 2 * q2 * ux) / m, 2 * (-q0 * uy + q1 * uz - 2 * q3 * ux) / m, 0, 0, 0], [(-2 * ux * (q0 * q3 + q1 * q2) + uy * (2 * q1**2 + 2 * q3**2 - 1) + 2 * uz * (q0 * q1 - q2 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (-q1 * uz + q3 * ux) / m, 2 * (-q0 * uz - 2 * q1 * uy + q2 * ux) / m, 2 * (q1 * ux + q3 * uz) / m, 2 * (q0 * ux + q2 * uz - 2 * q3 * uy) / m, 0, 0, 0], [(2 * ux * (q0 * q2 - q1 * q3) - 2 * uy * (q0 * q1 + q2 * q3) + uz * (2 * q1**2 + 2 * q2**2 - 1)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q1 * uy - q2 * ux) / m, 2 * (q0 * uy - 2 * q1 * uz + q3 * ux) / m, 2 * (-q0 * ux - 2 * q2 * uz + q3 * uy) / m, 2 * (q1 * ux + q2 * uy) / m, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -0.5 * wx, -0.5 * wy, - 0.5 * wz, -0.5 * q1, -0.5 * q2, -0.5 * q3], [0, 0, 0, 0, 0, 0, 0, 0.5 * wx, 0, 0.5 * wz, - 0.5 * wy, 0.5 * q0, -0.5 * q3, 0.5 * q2], [0, 0, 0, 0, 0, 0, 0, 0.5 * wy, -0.5 * wz, 0, 0.5 * wx, 0.5 * q3, 0.5 * q0, -0.5 * q1], [0, 0, 0, 0, 0, 0, 0, 0.5 * wz, 0.5 * wy, - 0.5 * wx, 0, -0.5 * q2, 0.5 * q1, 0.5 * q0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L150-L176
2
[ 0, 1, 3, 4, 5 ]
18.518519
[]
0
false
94.573643
27
1
100
0
def A_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [(ux * (2 * q2**2 + 2 * q3**2 - 1) + 2 * uy * (q0 * q3 - q1 * q2) - 2 * uz * (q0 * q2 + q1 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q2 * uz - q3 * uy) / m, 2 * (q2 * uy + q3 * uz) / m, 2 * (q0 * uz + q1 * uy - 2 * q2 * ux) / m, 2 * (-q0 * uy + q1 * uz - 2 * q3 * ux) / m, 0, 0, 0], [(-2 * ux * (q0 * q3 + q1 * q2) + uy * (2 * q1**2 + 2 * q3**2 - 1) + 2 * uz * (q0 * q1 - q2 * q3)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (-q1 * uz + q3 * ux) / m, 2 * (-q0 * uz - 2 * q1 * uy + q2 * ux) / m, 2 * (q1 * ux + q3 * uz) / m, 2 * (q0 * ux + q2 * uz - 2 * q3 * uy) / m, 0, 0, 0], [(2 * ux * (q0 * q2 - q1 * q3) - 2 * uy * (q0 * q1 + q2 * q3) + uz * (2 * q1**2 + 2 * q2**2 - 1)) / m**2, 0, 0, 0, 0, 0, 0, 2 * (q1 * uy - q2 * ux) / m, 2 * (q0 * uy - 2 * q1 * uz + q3 * ux) / m, 2 * (-q0 * ux - 2 * q2 * uz + q3 * uy) / m, 2 * (q1 * ux + q2 * uy) / m, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -0.5 * wx, -0.5 * wy, - 0.5 * wz, -0.5 * q1, -0.5 * q2, -0.5 * q3], [0, 0, 0, 0, 0, 0, 0, 0.5 * wx, 0, 0.5 * wz, - 0.5 * wy, 0.5 * q0, -0.5 * q3, 0.5 * q2], [0, 0, 0, 0, 0, 0, 0, 0.5 * wy, -0.5 * wz, 0, 0.5 * wx, 0.5 * q3, 0.5 * q0, -0.5 * q1], [0, 0, 0, 0, 0, 0, 0, 0.5 * wz, 0.5 * wy, - 0.5 * wx, 0, -0.5 * q2, 0.5 * q1, 0.5 * q0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
1,313
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.B_func
(self, x, u)
return np.array([ [-0.01 * ux / np.sqrt(ux**2 + uy**2 + uz**2), -0.01 * uy / np.sqrt(ux ** 2 + uy**2 + uz**2), -0.01 * uz / np.sqrt(ux**2 + uy**2 + uz**2)], [0, 0, 0], [0, 0, 0], [0, 0, 0], [(-2 * q2**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q3 + q1 * q2) / m, 2 * (q0 * q2 + q1 * q3) / m], [2 * (q0 * q3 + q1 * q2) / m, (-2 * q1**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q1 + q2 * q3) / m], [2 * (-q0 * q2 + q1 * q3) / m, 2 * (q0 * q1 + q2 * q3) / m, (-2 * q1**2 - 2 * q2**2 + 1) / m], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 1.0], [0, -1.0, 0] ])
178
203
def B_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [-0.01 * ux / np.sqrt(ux**2 + uy**2 + uz**2), -0.01 * uy / np.sqrt(ux ** 2 + uy**2 + uz**2), -0.01 * uz / np.sqrt(ux**2 + uy**2 + uz**2)], [0, 0, 0], [0, 0, 0], [0, 0, 0], [(-2 * q2**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q3 + q1 * q2) / m, 2 * (q0 * q2 + q1 * q3) / m], [2 * (q0 * q3 + q1 * q2) / m, (-2 * q1**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q1 + q2 * q3) / m], [2 * (-q0 * q2 + q1 * q3) / m, 2 * (q0 * q1 + q2 * q3) / m, (-2 * q1**2 - 2 * q2**2 + 1) / m], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 1.0], [0, -1.0, 0] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L178-L203
2
[ 0, 1, 3, 4, 5 ]
19.230769
[]
0
false
94.573643
26
1
100
0
def B_func(self, x, u): m, rx, ry, rz, vx, vy, vz, q0, q1, q2, q3, wx, wy, wz = x[0], x[1], x[ 2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13] ux, uy, uz = u[0], u[1], u[2] return np.array([ [-0.01 * ux / np.sqrt(ux**2 + uy**2 + uz**2), -0.01 * uy / np.sqrt(ux ** 2 + uy**2 + uz**2), -0.01 * uz / np.sqrt(ux**2 + uy**2 + uz**2)], [0, 0, 0], [0, 0, 0], [0, 0, 0], [(-2 * q2**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q3 + q1 * q2) / m, 2 * (q0 * q2 + q1 * q3) / m], [2 * (q0 * q3 + q1 * q2) / m, (-2 * q1**2 - 2 * q3**2 + 1) / m, 2 * (-q0 * q1 + q2 * q3) / m], [2 * (-q0 * q2 + q1 * q3) / m, 2 * (q0 * q1 + q2 * q3) / m, (-2 * q1**2 - 2 * q2**2 + 1) / m], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 1.0], [0, -1.0, 0] ])
1,314
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.euler_to_quat
(self, a)
return q
205
222
def euler_to_quat(self, a): a = np.deg2rad(a) cy = np.cos(a[1] * 0.5) sy = np.sin(a[1] * 0.5) cr = np.cos(a[0] * 0.5) sr = np.sin(a[0] * 0.5) cp = np.cos(a[2] * 0.5) sp = np.sin(a[2] * 0.5) q = np.zeros(4) q[0] = cy * cr * cp + sy * sr * sp q[1] = cy * sr * cp - sy * cr * sp q[3] = cy * cr * sp + sy * sr * cp q[2] = sy * cr * cp - cy * sr * sp return q
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L205-L222
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
94.573643
18
1
100
0
def euler_to_quat(self, a): a = np.deg2rad(a) cy = np.cos(a[1] * 0.5) sy = np.sin(a[1] * 0.5) cr = np.cos(a[0] * 0.5) sr = np.sin(a[0] * 0.5) cp = np.cos(a[2] * 0.5) sp = np.sin(a[2] * 0.5) q = np.zeros(4) q[0] = cy * cr * cp + sy * sr * sp q[1] = cy * sr * cp - sy * cr * sp q[3] = cy * cr * sp + sy * sr * cp q[2] = sy * cr * cp - cy * sr * sp return q
1,315
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.skew
(self, v)
return np.array([ [0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0] ])
224
229
def skew(self, v): return np.array([ [0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L224-L229
2
[ 0 ]
16.666667
[ 1 ]
16.666667
false
94.573643
6
1
83.333333
0
def skew(self, v): return np.array([ [0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0] ])
1,316
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.dir_cosine
(self, q)
return np.array([ [1 - 2 * (q[2] ** 2 + q[3] ** 2), 2 * (q[1] * q[2] + q[0] * q[3]), 2 * (q[1] * q[3] - q[0] * q[2])], [2 * (q[1] * q[2] - q[0] * q[3]), 1 - 2 * (q[1] ** 2 + q[3] ** 2), 2 * (q[2] * q[3] + q[0] * q[1])], [2 * (q[1] * q[3] + q[0] * q[2]), 2 * (q[2] * q[3] - q[0] * q[1]), 1 - 2 * (q[1] ** 2 + q[2] ** 2)] ])
231
239
def dir_cosine(self, q): return np.array([ [1 - 2 * (q[2] ** 2 + q[3] ** 2), 2 * (q[1] * q[2] + q[0] * q[3]), 2 * (q[1] * q[3] - q[0] * q[2])], [2 * (q[1] * q[2] - q[0] * q[3]), 1 - 2 * (q[1] ** 2 + q[3] ** 2), 2 * (q[2] * q[3] + q[0] * q[1])], [2 * (q[1] * q[3] + q[0] * q[2]), 2 * (q[2] * q[3] - q[0] * q[1]), 1 - 2 * (q[1] ** 2 + q[2] ** 2)] ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L231-L239
2
[ 0 ]
11.111111
[ 1 ]
11.111111
false
94.573643
9
1
88.888889
0
def dir_cosine(self, q): return np.array([ [1 - 2 * (q[2] ** 2 + q[3] ** 2), 2 * (q[1] * q[2] + q[0] * q[3]), 2 * (q[1] * q[3] - q[0] * q[2])], [2 * (q[1] * q[2] - q[0] * q[3]), 1 - 2 * (q[1] ** 2 + q[3] ** 2), 2 * (q[2] * q[3] + q[0] * q[1])], [2 * (q[1] * q[3] + q[0] * q[2]), 2 * (q[2] * q[3] - q[0] * q[1]), 1 - 2 * (q[1] ** 2 + q[2] ** 2)] ])
1,317
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.omega
(self, w)
return np.array([ [0, -w[0], -w[1], -w[2]], [w[0], 0, w[2], -w[1]], [w[1], -w[2], 0, w[0]], [w[2], w[1], -w[0], 0], ])
241
247
def omega(self, w): return np.array([ [0, -w[0], -w[1], -w[2]], [w[0], 0, w[2], -w[1]], [w[1], -w[2], 0, w[0]], [w[2], w[1], -w[0], 0], ])
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L241-L247
2
[ 0 ]
14.285714
[ 1 ]
14.285714
false
94.573643
7
1
85.714286
0
def omega(self, w): return np.array([ [0, -w[0], -w[1], -w[2]], [w[0], 0, w[2], -w[1]], [w[1], -w[2], 0, w[0]], [w[2], w[1], -w[0], 0], ])
1,318
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.initialize_trajectory
(self, X, U)
return X, U
Initialize the trajectory with linear approximation.
Initialize the trajectory with linear approximation.
249
268
def initialize_trajectory(self, X, U): """ Initialize the trajectory with linear approximation. """ K = X.shape[1] for k in range(K): alpha1 = (K - k) / K alpha2 = k / K m_k = (alpha1 * self.x_init[0] + alpha2 * self.x_final[0],) r_I_k = alpha1 * self.x_init[1:4] + alpha2 * self.x_final[1:4] v_I_k = alpha1 * self.x_init[4:7] + alpha2 * self.x_final[4:7] q_B_I_k = np.array([1, 0, 0, 0]) w_B_k = alpha1 * self.x_init[11:14] + alpha2 * self.x_final[11:14] X[:, k] = np.concatenate((m_k, r_I_k, v_I_k, q_B_I_k, w_B_k)) U[:, k] = m_k * -self.g_I return X, U
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L249-L268
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
94.573643
20
2
100
1
def initialize_trajectory(self, X, U): K = X.shape[1] for k in range(K): alpha1 = (K - k) / K alpha2 = k / K m_k = (alpha1 * self.x_init[0] + alpha2 * self.x_final[0],) r_I_k = alpha1 * self.x_init[1:4] + alpha2 * self.x_final[1:4] v_I_k = alpha1 * self.x_init[4:7] + alpha2 * self.x_final[4:7] q_B_I_k = np.array([1, 0, 0, 0]) w_B_k = alpha1 * self.x_init[11:14] + alpha2 * self.x_final[11:14] X[:, k] = np.concatenate((m_k, r_I_k, v_I_k, q_B_I_k, w_B_k)) U[:, k] = m_k * -self.g_I return X, U
1,319
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Rocket_Model_6DoF.get_constraints
(self, X_v, U_v, X_last_p, U_last_p)
return constraints
Get model specific constraints. :param X_v: cvx variable for current states :param U_v: cvx variable for current inputs :param X_last_p: cvx parameter for last states :param U_last_p: cvx parameter for last inputs :return: A list of cvx constraints
Get model specific constraints.
270
316
def get_constraints(self, X_v, U_v, X_last_p, U_last_p): """ Get model specific constraints. :param X_v: cvx variable for current states :param U_v: cvx variable for current inputs :param X_last_p: cvx parameter for last states :param U_last_p: cvx parameter for last inputs :return: A list of cvx constraints """ # Boundary conditions: constraints = [ X_v[0, 0] == self.x_init[0], X_v[1:4, 0] == self.x_init[1:4], X_v[4:7, 0] == self.x_init[4:7], # X_v[7:11, 0] == self.x_init[7:11], # initial orientation is free X_v[11:14, 0] == self.x_init[11:14], # X_[0, -1] final mass is free X_v[1:, -1] == self.x_final[1:], U_v[1:3, -1] == 0, ] constraints += [ # State constraints: X_v[0, :] >= self.m_dry, # minimum mass cvxpy.norm(X_v[2: 4, :], axis=0) <= X_v[1, :] / \ self.tan_gamma_gs, # glideslope cvxpy.norm(X_v[9:11, :], axis=0) <= np.sqrt( (1 - self.cos_theta_max) / 2), # maximum angle # maximum angular velocity cvxpy.norm(X_v[11: 14, :], axis=0) <= self.w_B_max, # Control constraints: cvxpy.norm(U_v[1:3, :], axis=0) <= self.tan_delta_max * \ U_v[0, :], # gimbal angle constraint cvxpy.norm(U_v, axis=0) <= self.T_max, # upper thrust constraint ] # linearized lower thrust constraint rhs = [U_last_p[:, k] / cvxpy.norm(U_last_p[:, k]) @ U_v[:, k] for k in range(X_v.shape[1])] constraints += [ self.T_min <= cvxpy.vstack(rhs) ] return constraints
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L270-L316
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 ]
100
[]
0
true
94.573643
47
2
100
7
def get_constraints(self, X_v, U_v, X_last_p, U_last_p): # Boundary conditions: constraints = [ X_v[0, 0] == self.x_init[0], X_v[1:4, 0] == self.x_init[1:4], X_v[4:7, 0] == self.x_init[4:7], # X_v[7:11, 0] == self.x_init[7:11], # initial orientation is free X_v[11:14, 0] == self.x_init[11:14], # X_[0, -1] final mass is free X_v[1:, -1] == self.x_final[1:], U_v[1:3, -1] == 0, ] constraints += [ # State constraints: X_v[0, :] >= self.m_dry, # minimum mass cvxpy.norm(X_v[2: 4, :], axis=0) <= X_v[1, :] / \ self.tan_gamma_gs, # glideslope cvxpy.norm(X_v[9:11, :], axis=0) <= np.sqrt( (1 - self.cos_theta_max) / 2), # maximum angle # maximum angular velocity cvxpy.norm(X_v[11: 14, :], axis=0) <= self.w_B_max, # Control constraints: cvxpy.norm(U_v[1:3, :], axis=0) <= self.tan_delta_max * \ U_v[0, :], # gimbal angle constraint cvxpy.norm(U_v, axis=0) <= self.T_max, # upper thrust constraint ] # linearized lower thrust constraint rhs = [U_last_p[:, k] / cvxpy.norm(U_last_p[:, k]) @ U_v[:, k] for k in range(X_v.shape[1])] constraints += [ self.T_min <= cvxpy.vstack(rhs) ] return constraints
1,320
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Integrator.__init__
(self, m, K)
320
352
def __init__(self, m, K): self.K = K self.m = m self.n_x = m.n_x self.n_u = m.n_u self.A_bar = np.zeros([m.n_x * m.n_x, K - 1]) self.B_bar = np.zeros([m.n_x * m.n_u, K - 1]) self.C_bar = np.zeros([m.n_x * m.n_u, K - 1]) self.S_bar = np.zeros([m.n_x, K - 1]) self.z_bar = np.zeros([m.n_x, K - 1]) # vector indices for flat matrices x_end = m.n_x A_bar_end = m.n_x * (1 + m.n_x) B_bar_end = m.n_x * (1 + m.n_x + m.n_u) C_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u) S_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u + 1) z_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u + 2) self.x_ind = slice(0, x_end) self.A_bar_ind = slice(x_end, A_bar_end) self.B_bar_ind = slice(A_bar_end, B_bar_end) self.C_bar_ind = slice(B_bar_end, C_bar_end) self.S_bar_ind = slice(C_bar_end, S_bar_end) self.z_bar_ind = slice(S_bar_end, z_bar_end) self.f, self.A, self.B = m.f_func, m.A_func, m.B_func # integration initial condition self.V0 = np.zeros((m.n_x * (1 + m.n_x + m.n_u + m.n_u + 2),)) self.V0[self.A_bar_ind] = np.eye(m.n_x).reshape(-1) self.dt = 1. / (K - 1)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L320-L352
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
94.573643
33
1
100
0
def __init__(self, m, K): self.K = K self.m = m self.n_x = m.n_x self.n_u = m.n_u self.A_bar = np.zeros([m.n_x * m.n_x, K - 1]) self.B_bar = np.zeros([m.n_x * m.n_u, K - 1]) self.C_bar = np.zeros([m.n_x * m.n_u, K - 1]) self.S_bar = np.zeros([m.n_x, K - 1]) self.z_bar = np.zeros([m.n_x, K - 1]) # vector indices for flat matrices x_end = m.n_x A_bar_end = m.n_x * (1 + m.n_x) B_bar_end = m.n_x * (1 + m.n_x + m.n_u) C_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u) S_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u + 1) z_bar_end = m.n_x * (1 + m.n_x + m.n_u + m.n_u + 2) self.x_ind = slice(0, x_end) self.A_bar_ind = slice(x_end, A_bar_end) self.B_bar_ind = slice(A_bar_end, B_bar_end) self.C_bar_ind = slice(B_bar_end, C_bar_end) self.S_bar_ind = slice(C_bar_end, S_bar_end) self.z_bar_ind = slice(S_bar_end, z_bar_end) self.f, self.A, self.B = m.f_func, m.A_func, m.B_func # integration initial condition self.V0 = np.zeros((m.n_x * (1 + m.n_x + m.n_u + m.n_u + 2),)) self.V0[self.A_bar_ind] = np.eye(m.n_x).reshape(-1) self.dt = 1. / (K - 1)
1,321
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Integrator.calculate_discretization
(self, X, U, sigma)
return self.A_bar, self.B_bar, self.C_bar, self.S_bar, self.z_bar
Calculate discretization for given states, inputs and total time. :param X: Matrix of states for all time points :param U: Matrix of inputs for all time points :param sigma: Total time :return: The discretization matrices
Calculate discretization for given states, inputs and total time.
354
379
def calculate_discretization(self, X, U, sigma): """ Calculate discretization for given states, inputs and total time. :param X: Matrix of states for all time points :param U: Matrix of inputs for all time points :param sigma: Total time :return: The discretization matrices """ for k in range(self.K - 1): self.V0[self.x_ind] = X[:, k] V = np.array(odeint(self._ode_dVdt, self.V0, (0, self.dt), args=(U[:, k], U[:, k + 1], sigma))[1, :]) # using \Phi_A(\tau_{k+1},\xi) = \Phi_A(\tau_{k+1},\tau_k)\Phi_A(\xi,\tau_k)^{-1} # flatten matrices in column-major (Fortran) order for CVXPY Phi = V[self.A_bar_ind].reshape((self.n_x, self.n_x)) self.A_bar[:, k] = Phi.flatten(order='F') self.B_bar[:, k] = np.matmul(Phi, V[self.B_bar_ind].reshape( (self.n_x, self.n_u))).flatten(order='F') self.C_bar[:, k] = np.matmul(Phi, V[self.C_bar_ind].reshape( (self.n_x, self.n_u))).flatten(order='F') self.S_bar[:, k] = np.matmul(Phi, V[self.S_bar_ind]) self.z_bar[:, k] = np.matmul(Phi, V[self.z_bar_ind]) return self.A_bar, self.B_bar, self.C_bar, self.S_bar, self.z_bar
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L354-L379
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 ]
100
[]
0
true
94.573643
26
2
100
6
def calculate_discretization(self, X, U, sigma): for k in range(self.K - 1): self.V0[self.x_ind] = X[:, k] V = np.array(odeint(self._ode_dVdt, self.V0, (0, self.dt), args=(U[:, k], U[:, k + 1], sigma))[1, :]) # using \Phi_A(\tau_{k+1},\xi) = \Phi_A(\tau_{k+1},\tau_k)\Phi_A(\xi,\tau_k)^{-1} # flatten matrices in column-major (Fortran) order for CVXPY Phi = V[self.A_bar_ind].reshape((self.n_x, self.n_x)) self.A_bar[:, k] = Phi.flatten(order='F') self.B_bar[:, k] = np.matmul(Phi, V[self.B_bar_ind].reshape( (self.n_x, self.n_u))).flatten(order='F') self.C_bar[:, k] = np.matmul(Phi, V[self.C_bar_ind].reshape( (self.n_x, self.n_u))).flatten(order='F') self.S_bar[:, k] = np.matmul(Phi, V[self.S_bar_ind]) self.z_bar[:, k] = np.matmul(Phi, V[self.z_bar_ind]) return self.A_bar, self.B_bar, self.C_bar, self.S_bar, self.z_bar
1,322
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
Integrator._ode_dVdt
(self, V, t, u_t0, u_t1, sigma)
return dVdt
ODE function to compute dVdt. :param V: Evaluation state V = [x, Phi_A, B_bar, C_bar, S_bar, z_bar] :param t: Evaluation time :param u_t0: Input at start of interval :param u_t1: Input at end of interval :param sigma: Total time :return: Derivative at current time and state dVdt
ODE function to compute dVdt.
381
416
def _ode_dVdt(self, V, t, u_t0, u_t1, sigma): """ ODE function to compute dVdt. :param V: Evaluation state V = [x, Phi_A, B_bar, C_bar, S_bar, z_bar] :param t: Evaluation time :param u_t0: Input at start of interval :param u_t1: Input at end of interval :param sigma: Total time :return: Derivative at current time and state dVdt """ alpha = (self.dt - t) / self.dt beta = t / self.dt x = V[self.x_ind] u = u_t0 + beta * (u_t1 - u_t0) # using \Phi_A(\tau_{k+1},\xi) = \Phi_A(\tau_{k+1},\tau_k)\Phi_A(\xi,\tau_k)^{-1} # and pre-multiplying with \Phi_A(\tau_{k+1},\tau_k) after integration Phi_A_xi = np.linalg.inv( V[self.A_bar_ind].reshape((self.n_x, self.n_x))) A_subs = sigma * self.A(x, u) B_subs = sigma * self.B(x, u) f_subs = self.f(x, u) dVdt = np.zeros_like(V) dVdt[self.x_ind] = sigma * f_subs.transpose() dVdt[self.A_bar_ind] = np.matmul( A_subs, V[self.A_bar_ind].reshape((self.n_x, self.n_x))).reshape(-1) dVdt[self.B_bar_ind] = np.matmul(Phi_A_xi, B_subs).reshape(-1) * alpha dVdt[self.C_bar_ind] = np.matmul(Phi_A_xi, B_subs).reshape(-1) * beta dVdt[self.S_bar_ind] = np.matmul(Phi_A_xi, f_subs).transpose() z_t = -np.matmul(A_subs, x) - np.matmul(B_subs, u) dVdt[self.z_bar_ind] = np.dot(Phi_A_xi, z_t.T).flatten() return dVdt
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L381-L416
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 ]
100
[]
0
true
94.573643
36
1
100
8
def _ode_dVdt(self, V, t, u_t0, u_t1, sigma): alpha = (self.dt - t) / self.dt beta = t / self.dt x = V[self.x_ind] u = u_t0 + beta * (u_t1 - u_t0) # using \Phi_A(\tau_{k+1},\xi) = \Phi_A(\tau_{k+1},\tau_k)\Phi_A(\xi,\tau_k)^{-1} # and pre-multiplying with \Phi_A(\tau_{k+1},\tau_k) after integration Phi_A_xi = np.linalg.inv( V[self.A_bar_ind].reshape((self.n_x, self.n_x))) A_subs = sigma * self.A(x, u) B_subs = sigma * self.B(x, u) f_subs = self.f(x, u) dVdt = np.zeros_like(V) dVdt[self.x_ind] = sigma * f_subs.transpose() dVdt[self.A_bar_ind] = np.matmul( A_subs, V[self.A_bar_ind].reshape((self.n_x, self.n_x))).reshape(-1) dVdt[self.B_bar_ind] = np.matmul(Phi_A_xi, B_subs).reshape(-1) * alpha dVdt[self.C_bar_ind] = np.matmul(Phi_A_xi, B_subs).reshape(-1) * beta dVdt[self.S_bar_ind] = np.matmul(Phi_A_xi, f_subs).transpose() z_t = -np.matmul(A_subs, x) - np.matmul(B_subs, u) dVdt[self.z_bar_ind] = np.dot(Phi_A_xi, z_t.T).flatten() return dVdt
1,323
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
SCProblem.__init__
(self, m, K)
428
500
def __init__(self, m, K): # Variables: self.var = dict() self.var['X'] = cvxpy.Variable((m.n_x, K)) self.var['U'] = cvxpy.Variable((m.n_u, K)) self.var['sigma'] = cvxpy.Variable(nonneg=True) self.var['nu'] = cvxpy.Variable((m.n_x, K - 1)) self.var['delta_norm'] = cvxpy.Variable(nonneg=True) self.var['sigma_norm'] = cvxpy.Variable(nonneg=True) # Parameters: self.par = dict() self.par['A_bar'] = cvxpy.Parameter((m.n_x * m.n_x, K - 1)) self.par['B_bar'] = cvxpy.Parameter((m.n_x * m.n_u, K - 1)) self.par['C_bar'] = cvxpy.Parameter((m.n_x * m.n_u, K - 1)) self.par['S_bar'] = cvxpy.Parameter((m.n_x, K - 1)) self.par['z_bar'] = cvxpy.Parameter((m.n_x, K - 1)) self.par['X_last'] = cvxpy.Parameter((m.n_x, K)) self.par['U_last'] = cvxpy.Parameter((m.n_u, K)) self.par['sigma_last'] = cvxpy.Parameter(nonneg=True) self.par['weight_sigma'] = cvxpy.Parameter(nonneg=True) self.par['weight_delta'] = cvxpy.Parameter(nonneg=True) self.par['weight_delta_sigma'] = cvxpy.Parameter(nonneg=True) self.par['weight_nu'] = cvxpy.Parameter(nonneg=True) # Constraints: constraints = [] # Model: constraints += m.get_constraints( self.var['X'], self.var['U'], self.par['X_last'], self.par['U_last']) # Dynamics: # x_t+1 = A_*x_t+B_*U_t+C_*U_T+1*S_*sigma+zbar+nu constraints += [ self.var['X'][:, k + 1] == cvxpy.reshape(self.par['A_bar'][:, k], (m.n_x, m.n_x)) @ self.var['X'][:, k] + cvxpy.reshape(self.par['B_bar'][:, k], (m.n_x, m.n_u)) @ self.var['U'][:, k] + cvxpy.reshape(self.par['C_bar'][:, k], (m.n_x, m.n_u)) @ self.var['U'][:, k + 1] + self.par['S_bar'][:, k] * self.var['sigma'] + self.par['z_bar'][:, k] + self.var['nu'][:, k] for k in range(K - 1) ] # Trust regions: dx = cvxpy.sum(cvxpy.square( self.var['X'] - self.par['X_last']), axis=0) du = cvxpy.sum(cvxpy.square( self.var['U'] - self.par['U_last']), axis=0) ds = self.var['sigma'] - self.par['sigma_last'] constraints += [cvxpy.norm(dx + du, 1) <= self.var['delta_norm']] constraints += [cvxpy.norm(ds, 'inf') <= self.var['sigma_norm']] # Flight time positive: constraints += [self.var['sigma'] >= 0.1] # Objective: sc_objective = cvxpy.Minimize( self.par['weight_sigma'] * self.var['sigma'] + self.par['weight_nu'] * cvxpy.norm(self.var['nu'], 'inf') + self.par['weight_delta'] * self.var['delta_norm'] + self.par['weight_delta_sigma'] * self.var['sigma_norm'] ) objective = sc_objective self.prob = cvxpy.Problem(objective, constraints)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L428-L500
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, 35, 36, 50, 51, 53, 55, 56, 57, 58, 59, 60, 61, 62, 63, 69, 70, 71, 72 ]
68.493151
[]
0
false
94.573643
73
2
100
0
def __init__(self, m, K): # Variables: self.var = dict() self.var['X'] = cvxpy.Variable((m.n_x, K)) self.var['U'] = cvxpy.Variable((m.n_u, K)) self.var['sigma'] = cvxpy.Variable(nonneg=True) self.var['nu'] = cvxpy.Variable((m.n_x, K - 1)) self.var['delta_norm'] = cvxpy.Variable(nonneg=True) self.var['sigma_norm'] = cvxpy.Variable(nonneg=True) # Parameters: self.par = dict() self.par['A_bar'] = cvxpy.Parameter((m.n_x * m.n_x, K - 1)) self.par['B_bar'] = cvxpy.Parameter((m.n_x * m.n_u, K - 1)) self.par['C_bar'] = cvxpy.Parameter((m.n_x * m.n_u, K - 1)) self.par['S_bar'] = cvxpy.Parameter((m.n_x, K - 1)) self.par['z_bar'] = cvxpy.Parameter((m.n_x, K - 1)) self.par['X_last'] = cvxpy.Parameter((m.n_x, K)) self.par['U_last'] = cvxpy.Parameter((m.n_u, K)) self.par['sigma_last'] = cvxpy.Parameter(nonneg=True) self.par['weight_sigma'] = cvxpy.Parameter(nonneg=True) self.par['weight_delta'] = cvxpy.Parameter(nonneg=True) self.par['weight_delta_sigma'] = cvxpy.Parameter(nonneg=True) self.par['weight_nu'] = cvxpy.Parameter(nonneg=True) # Constraints: constraints = [] # Model: constraints += m.get_constraints( self.var['X'], self.var['U'], self.par['X_last'], self.par['U_last']) # Dynamics: # x_t+1 = A_*x_t+B_*U_t+C_*U_T+1*S_*sigma+zbar+nu constraints += [ self.var['X'][:, k + 1] == cvxpy.reshape(self.par['A_bar'][:, k], (m.n_x, m.n_x)) @ self.var['X'][:, k] + cvxpy.reshape(self.par['B_bar'][:, k], (m.n_x, m.n_u)) @ self.var['U'][:, k] + cvxpy.reshape(self.par['C_bar'][:, k], (m.n_x, m.n_u)) @ self.var['U'][:, k + 1] + self.par['S_bar'][:, k] * self.var['sigma'] + self.par['z_bar'][:, k] + self.var['nu'][:, k] for k in range(K - 1) ] # Trust regions: dx = cvxpy.sum(cvxpy.square( self.var['X'] - self.par['X_last']), axis=0) du = cvxpy.sum(cvxpy.square( self.var['U'] - self.par['U_last']), axis=0) ds = self.var['sigma'] - self.par['sigma_last'] constraints += [cvxpy.norm(dx + du, 1) <= self.var['delta_norm']] constraints += [cvxpy.norm(ds, 'inf') <= self.var['sigma_norm']] # Flight time positive: constraints += [self.var['sigma'] >= 0.1] # Objective: sc_objective = cvxpy.Minimize( self.par['weight_sigma'] * self.var['sigma'] + self.par['weight_nu'] * cvxpy.norm(self.var['nu'], 'inf') + self.par['weight_delta'] * self.var['delta_norm'] + self.par['weight_delta_sigma'] * self.var['sigma_norm'] ) objective = sc_objective self.prob = cvxpy.Problem(objective, constraints)
1,324
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
SCProblem.set_parameters
(self, **kwargs)
All parameters have to be filled before calling solve(). Takes the following arguments as keywords: A_bar B_bar C_bar S_bar z_bar X_last U_last sigma_last E weight_sigma weight_nu radius_trust_region
All parameters have to be filled before calling solve(). Takes the following arguments as keywords:
502
525
def set_parameters(self, **kwargs): """ All parameters have to be filled before calling solve(). Takes the following arguments as keywords: A_bar B_bar C_bar S_bar z_bar X_last U_last sigma_last E weight_sigma weight_nu radius_trust_region """ for key in kwargs: if key in self.par: self.par[key].value = kwargs[key] else: print(f'Parameter \'{key}\' does not exist.')
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L502-L525
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
95.833333
[ 23 ]
4.166667
false
94.573643
24
3
95.833333
15
def set_parameters(self, **kwargs): for key in kwargs: if key in self.par: self.par[key].value = kwargs[key] else: print(f'Parameter \'{key}\' does not exist.')
1,325
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
SCProblem.get_variable
(self, name)
527
532
def get_variable(self, name): if name in self.var: return self.var[name].value else: print(f'Variable \'{name}\' does not exist.') return None
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L527-L532
2
[ 0, 1, 2 ]
50
[ 4, 5 ]
33.333333
false
94.573643
6
2
66.666667
0
def get_variable(self, name): if name in self.var: return self.var[name].value else: print(f'Variable \'{name}\' does not exist.') return None
1,326
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
AerialNavigation/rocket_powered_landing/rocket_powered_landing.py
SCProblem.solve
(self, **kwargs)
return info
534
551
def solve(self, **kwargs): error = False try: self.prob.solve(verbose=verbose_solver, solver=solver) except cvxpy.SolverError: error = True stats = self.prob.solver_stats info = { 'setup_time': stats.setup_time, 'solver_time': stats.solve_time, 'iterations': stats.num_iters, 'solver_error': error } return info
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/AerialNavigation/rocket_powered_landing/rocket_powered_landing.py#L534-L551
2
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 16, 17 ]
66.666667
[]
0
false
94.573643
18
2
100
0
def solve(self, **kwargs): error = False try: self.prob.solve(verbose=verbose_solver, solver=solver) except cvxpy.SolverError: error = True stats = self.prob.solver_stats info = { 'setup_time': stats.setup_time, 'solver_time': stats.solve_time, 'iterations': stats.num_iters, 'solver_error': error } return info
1,327
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
fast_slam2
(particles, u, z)
return particles
49
56
def fast_slam2(particles, u, z): particles = predict_particles(particles, u) particles = update_with_observation(particles, z) particles = resampling(particles) return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L49-L56
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
97.046414
8
1
100
0
def fast_slam2(particles, u, z): particles = predict_particles(particles, u) particles = update_with_observation(particles, z) particles = resampling(particles) return particles
1,328
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
normalize_weight
(particles)
return particles
59
71
def normalize_weight(particles): sum_w = sum([p.w for p in particles]) try: for i in range(N_PARTICLE): particles[i].w /= sum_w except ZeroDivisionError: for i in range(N_PARTICLE): particles[i].w = 1.0 / N_PARTICLE return particles return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L59-L71
2
[ 0, 1, 2, 3, 4, 5, 11, 12 ]
61.538462
[ 6, 7, 8, 10 ]
30.769231
false
97.046414
13
5
69.230769
0
def normalize_weight(particles): sum_w = sum([p.w for p in particles]) try: for i in range(N_PARTICLE): particles[i].w /= sum_w except ZeroDivisionError: for i in range(N_PARTICLE): particles[i].w = 1.0 / N_PARTICLE return particles return particles
1,329
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
calc_final_state
(particles)
return xEst
74
86
def calc_final_state(particles): xEst = np.zeros((STATE_SIZE, 1)) particles = normalize_weight(particles) for i in range(N_PARTICLE): xEst[0, 0] += particles[i].w * particles[i].x xEst[1, 0] += particles[i].w * particles[i].y xEst[2, 0] += particles[i].w * particles[i].yaw xEst[2, 0] = pi_2_pi(xEst[2, 0]) return xEst
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L74-L86
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
97.046414
13
2
100
0
def calc_final_state(particles): xEst = np.zeros((STATE_SIZE, 1)) particles = normalize_weight(particles) for i in range(N_PARTICLE): xEst[0, 0] += particles[i].w * particles[i].x xEst[1, 0] += particles[i].w * particles[i].y xEst[2, 0] += particles[i].w * particles[i].yaw xEst[2, 0] = pi_2_pi(xEst[2, 0]) return xEst
1,330
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
predict_particles
(particles, u)
return particles
89
101
def predict_particles(particles, u): for i in range(N_PARTICLE): px = np.zeros((STATE_SIZE, 1)) px[0, 0] = particles[i].x px[1, 0] = particles[i].y px[2, 0] = particles[i].yaw ud = u + (np.random.randn(1, 2) @ R ** 0.5).T # add noise px = motion_model(px, ud) particles[i].x = px[0, 0] particles[i].y = px[1, 0] particles[i].yaw = px[2, 0] return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L89-L101
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
97.046414
13
2
100
0
def predict_particles(particles, u): for i in range(N_PARTICLE): px = np.zeros((STATE_SIZE, 1)) px[0, 0] = particles[i].x px[1, 0] = particles[i].y px[2, 0] = particles[i].yaw ud = u + (np.random.randn(1, 2) @ R ** 0.5).T # add noise px = motion_model(px, ud) particles[i].x = px[0, 0] particles[i].y = px[1, 0] particles[i].yaw = px[2, 0] return particles
1,331
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
add_new_lm
(particle, z, Q_cov)
return particle
104
125
def add_new_lm(particle, z, Q_cov): r = z[0] b = z[1] lm_id = int(z[2]) s = math.sin(pi_2_pi(particle.yaw + b)) c = math.cos(pi_2_pi(particle.yaw + b)) particle.lm[lm_id, 0] = particle.x + r * c particle.lm[lm_id, 1] = particle.y + r * s # covariance dx = r * c dy = r * s d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) Gz = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) particle.lmP[2 * lm_id:2 * lm_id + 2] = np.linalg.inv( Gz) @ Q_cov @ np.linalg.inv(Gz.T) return particle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L104-L125
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21 ]
90.909091
[]
0
false
97.046414
22
1
100
0
def add_new_lm(particle, z, Q_cov): r = z[0] b = z[1] lm_id = int(z[2]) s = math.sin(pi_2_pi(particle.yaw + b)) c = math.cos(pi_2_pi(particle.yaw + b)) particle.lm[lm_id, 0] = particle.x + r * c particle.lm[lm_id, 1] = particle.y + r * s # covariance dx = r * c dy = r * s d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) Gz = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) particle.lmP[2 * lm_id:2 * lm_id + 2] = np.linalg.inv( Gz) @ Q_cov @ np.linalg.inv(Gz.T) return particle
1,332
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
compute_jacobians
(particle, xf, Pf, Q_cov)
return zp, Hv, Hf, Sf
128
145
def compute_jacobians(particle, xf, Pf, Q_cov): dx = xf[0, 0] - particle.x dy = xf[1, 0] - particle.y d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) zp = np.array( [d, pi_2_pi(math.atan2(dy, dx) - particle.yaw)]).reshape(2, 1) Hv = np.array([[-dx / d, -dy / d, 0.0], [dy / d2, -dx / d2, -1.0]]) Hf = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) Sf = Hf @ Pf @ Hf.T + Q_cov return zp, Hv, Hf, Sf
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L128-L145
2
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17 ]
83.333333
[]
0
false
97.046414
18
1
100
0
def compute_jacobians(particle, xf, Pf, Q_cov): dx = xf[0, 0] - particle.x dy = xf[1, 0] - particle.y d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) zp = np.array( [d, pi_2_pi(math.atan2(dy, dx) - particle.yaw)]).reshape(2, 1) Hv = np.array([[-dx / d, -dy / d, 0.0], [dy / d2, -dx / d2, -1.0]]) Hf = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) Sf = Hf @ Pf @ Hf.T + Q_cov return zp, Hv, Hf, Sf
1,333
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
update_kf_with_cholesky
(xf, Pf, v, Q_cov, Hf)
return x, P
148
161
def update_kf_with_cholesky(xf, Pf, v, Q_cov, Hf): PHt = Pf @ Hf.T S = Hf @ PHt + Q_cov S = (S + S.T) * 0.5 SChol = np.linalg.cholesky(S).T SCholInv = np.linalg.inv(SChol) W1 = PHt @ SCholInv W = W1 @ SCholInv.T x = xf + W @ v P = Pf - W1 @ W1.T return x, P
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L148-L161
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
97.046414
14
1
100
0
def update_kf_with_cholesky(xf, Pf, v, Q_cov, Hf): PHt = Pf @ Hf.T S = Hf @ PHt + Q_cov S = (S + S.T) * 0.5 SChol = np.linalg.cholesky(S).T SCholInv = np.linalg.inv(SChol) W1 = PHt @ SCholInv W = W1 @ SCholInv.T x = xf + W @ v P = Pf - W1 @ W1.T return x, P
1,334
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
update_landmark
(particle, z, Q_cov)
return particle
164
179
def update_landmark(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) xf, Pf = update_kf_with_cholesky(xf, Pf, dz, Q, Hf) particle.lm[lm_id, :] = xf.T particle.lmP[2 * lm_id:2 * lm_id + 2, :] = Pf return particle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L164-L179
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
97.046414
16
1
100
0
def update_landmark(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) xf, Pf = update_kf_with_cholesky(xf, Pf, dz, Q, Hf) particle.lm[lm_id, :] = xf.T particle.lmP[2 * lm_id:2 * lm_id + 2, :] = Pf return particle
1,335
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
compute_weight
(particle, z, Q_cov)
return w
182
201
def compute_weight(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) try: invS = np.linalg.inv(Sf) except np.linalg.linalg.LinAlgError: return 1.0 num = math.exp(-0.5 * dz.T @ invS @ dz) den = 2.0 * math.pi * math.sqrt(np.linalg.det(Sf)) w = num / den return w
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L182-L201
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14, 15, 16, 17, 18, 19 ]
90
[ 11, 12 ]
10
false
97.046414
20
2
90
0
def compute_weight(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) try: invS = np.linalg.inv(Sf) except np.linalg.linalg.LinAlgError: return 1.0 num = math.exp(-0.5 * dz.T @ invS @ dz) den = 2.0 * math.pi * math.sqrt(np.linalg.det(Sf)) w = num / den return w
1,336
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
proposal_sampling
(particle, z, Q_cov)
return particle
204
226
def proposal_sampling(particle, z, Q_cov): lm_id = int(z[2]) xf = particle.lm[lm_id, :].reshape(2, 1) Pf = particle.lmP[2 * lm_id:2 * lm_id + 2] # State x = np.array([particle.x, particle.y, particle.yaw]).reshape(3, 1) P = particle.P zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) Sfi = np.linalg.inv(Sf) dz = z[0:2].reshape(2, 1) - zp dz[1] = pi_2_pi(dz[1]) Pi = np.linalg.inv(P) particle.P = np.linalg.inv(Hv.T @ Sfi @ Hv + Pi) # proposal covariance x += particle.P @ Hv.T @ Sfi @ dz # proposal mean particle.x = x[0, 0] particle.y = x[1, 0] particle.yaw = x[2, 0] return particle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L204-L226
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
100
[]
0
true
97.046414
23
1
100
0
def proposal_sampling(particle, z, Q_cov): lm_id = int(z[2]) xf = particle.lm[lm_id, :].reshape(2, 1) Pf = particle.lmP[2 * lm_id:2 * lm_id + 2] # State x = np.array([particle.x, particle.y, particle.yaw]).reshape(3, 1) P = particle.P zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) Sfi = np.linalg.inv(Sf) dz = z[0:2].reshape(2, 1) - zp dz[1] = pi_2_pi(dz[1]) Pi = np.linalg.inv(P) particle.P = np.linalg.inv(Hv.T @ Sfi @ Hv + Pi) # proposal covariance x += particle.P @ Hv.T @ Sfi @ dz # proposal mean particle.x = x[0, 0] particle.y = x[1, 0] particle.yaw = x[2, 0] return particle
1,337
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
update_with_observation
(particles, z)
return particles
229
245
def update_with_observation(particles, z): for iz in range(len(z[0, :])): landmark_id = int(z[2, iz]) for ip in range(N_PARTICLE): # new landmark if abs(particles[ip].lm[landmark_id, 0]) <= 0.01: particles[ip] = add_new_lm(particles[ip], z[:, iz], Q) # known landmark else: w = compute_weight(particles[ip], z[:, iz], Q) particles[ip].w *= w particles[ip] = update_landmark(particles[ip], z[:, iz], Q) particles[ip] = proposal_sampling(particles[ip], z[:, iz], Q) return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L229-L245
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16 ]
94.117647
[]
0
false
97.046414
17
4
100
0
def update_with_observation(particles, z): for iz in range(len(z[0, :])): landmark_id = int(z[2, iz]) for ip in range(N_PARTICLE): # new landmark if abs(particles[ip].lm[landmark_id, 0]) <= 0.01: particles[ip] = add_new_lm(particles[ip], z[:, iz], Q) # known landmark else: w = compute_weight(particles[ip], z[:, iz], Q) particles[ip].w *= w particles[ip] = update_landmark(particles[ip], z[:, iz], Q) particles[ip] = proposal_sampling(particles[ip], z[:, iz], Q) return particles
1,338
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
resampling
(particles)
return particles
low variance re-sampling
low variance re-sampling
248
285
def resampling(particles): """ low variance re-sampling """ particles = normalize_weight(particles) pw = [] for i in range(N_PARTICLE): pw.append(particles[i].w) pw = np.array(pw) n_eff = 1.0 / (pw @ pw.T) # Effective particle number if n_eff < NTH: # resampling w_cum = np.cumsum(pw) base = np.cumsum(pw * 0.0 + 1 / N_PARTICLE) - 1 / N_PARTICLE resample_id = base + np.random.rand(base.shape[0]) / N_PARTICLE inds = [] ind = 0 for ip in range(N_PARTICLE): while (ind < w_cum.shape[0] - 1) \ and (resample_id[ip] > w_cum[ind]): ind += 1 inds.append(ind) tmp_particles = particles[:] for i in range(len(inds)): particles[i].x = tmp_particles[inds[i]].x particles[i].y = tmp_particles[inds[i]].y particles[i].yaw = tmp_particles[inds[i]].yaw particles[i].lm = tmp_particles[inds[i]].lm[:, :] particles[i].lmP = tmp_particles[inds[i]].lmP[:, :] particles[i].w = 1.0 / N_PARTICLE return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L248-L285
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 ]
100
[]
0
true
97.046414
38
7
100
1
def resampling(particles): particles = normalize_weight(particles) pw = [] for i in range(N_PARTICLE): pw.append(particles[i].w) pw = np.array(pw) n_eff = 1.0 / (pw @ pw.T) # Effective particle number if n_eff < NTH: # resampling w_cum = np.cumsum(pw) base = np.cumsum(pw * 0.0 + 1 / N_PARTICLE) - 1 / N_PARTICLE resample_id = base + np.random.rand(base.shape[0]) / N_PARTICLE inds = [] ind = 0 for ip in range(N_PARTICLE): while (ind < w_cum.shape[0] - 1) \ and (resample_id[ip] > w_cum[ind]): ind += 1 inds.append(ind) tmp_particles = particles[:] for i in range(len(inds)): particles[i].x = tmp_particles[inds[i]].x particles[i].y = tmp_particles[inds[i]].y particles[i].yaw = tmp_particles[inds[i]].yaw particles[i].lm = tmp_particles[inds[i]].lm[:, :] particles[i].lmP = tmp_particles[inds[i]].lmP[:, :] particles[i].w = 1.0 / N_PARTICLE return particles
1,339
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
calc_input
(time)
return u
288
298
def calc_input(time): if time <= 3.0: # wait at first v = 0.0 yaw_rate = 0.0 else: v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([v, yaw_rate]).reshape(2, 1) return u
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L288-L298
2
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10 ]
90.909091
[]
0
false
97.046414
11
2
100
0
def calc_input(time): if time <= 3.0: # wait at first v = 0.0 yaw_rate = 0.0 else: v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([v, yaw_rate]).reshape(2, 1) return u
1,340
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
observation
(xTrue, xd, u, RFID)
return xTrue, z, xd, ud
301
329
def observation(xTrue, xd, u, RFID): # calc true state xTrue = motion_model(xTrue, u) # add noise to range observation z = np.zeros((3, 0)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_noise = np.random.randn() * Q_sim[1, 1] ** 0.5 angle_with_noise = angle + angle_noise # add noise zi = np.array([dn, pi_2_pi(angle_with_noise), i]).reshape(3, 1) z = np.hstack((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 + OFFSET_YAW_RATE_NOISE ud = np.array([ud1, ud2]).reshape(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L301-L329
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28 ]
96.551724
[]
0
false
97.046414
29
3
100
0
def observation(xTrue, xd, u, RFID): # calc true state xTrue = motion_model(xTrue, u) # add noise to range observation z = np.zeros((3, 0)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_noise = np.random.randn() * Q_sim[1, 1] ** 0.5 angle_with_noise = angle + angle_noise # add noise zi = np.array([dn, pi_2_pi(angle_with_noise), i]).reshape(3, 1) z = np.hstack((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 + OFFSET_YAW_RATE_NOISE ud = np.array([ud1, ud2]).reshape(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
1,341
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
motion_model
(x, u)
return x
332
345
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u x[2, 0] = pi_2_pi(x[2, 0]) return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L332-L345
2
[ 0, 1, 4, 5, 8, 9, 10, 11, 12, 13 ]
71.428571
[]
0
false
97.046414
14
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u x[2, 0] = pi_2_pi(x[2, 0]) return x
1,342
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
348
349
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L348-L349
2
[ 0, 1 ]
100
[]
0
true
97.046414
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
1,343
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
main
()
352
421
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [15.0, 15.0], [10.0, 20.0], [3.0, 15.0], [-5.0, 20.0], [-5.0, 5.0], [-10.0, 15.0] ]) n_landmark = RFID.shape[0] # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) # SLAM estimation xTrue = np.zeros((STATE_SIZE, 1)) # True state xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue particles = [Particle(n_landmark) for _ in range(N_PARTICLE)] while SIM_TIME >= time: time += DT u = calc_input(time) xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) particles = fast_slam2(particles, ud, z) xEst = calc_final_state(particles) x_state = xEst[0: STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") for iz in range(len(z[:, 0])): landmark_id = int(z[2, iz]) plt.plot([xEst[0], RFID[landmark_id, 0]], [ xEst[1], RFID[landmark_id, 1]], "-k") for i in range(N_PARTICLE): plt.plot(particles[i].x, particles[i].y, ".r") plt.plot(particles[i].lm[:, 0], particles[i].lm[:, 1], "xb") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.plot(xEst[0], xEst[1], "xk") plt.axis("equal") plt.grid(True) plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L352-L421
2
[ 0, 1, 2, 3, 4, 5, 6, 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 ]
71.698113
[]
0
false
97.046414
70
6
100
0
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [15.0, 15.0], [10.0, 20.0], [3.0, 15.0], [-5.0, 20.0], [-5.0, 5.0], [-10.0, 15.0] ]) n_landmark = RFID.shape[0] # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) # SLAM estimation xTrue = np.zeros((STATE_SIZE, 1)) # True state xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue particles = [Particle(n_landmark) for _ in range(N_PARTICLE)] while SIM_TIME >= time: time += DT u = calc_input(time) xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) particles = fast_slam2(particles, ud, z) xEst = calc_final_state(particles) x_state = xEst[0: STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") for iz in range(len(z[:, 0])): landmark_id = int(z[2, iz]) plt.plot([xEst[0], RFID[landmark_id, 0]], [ xEst[1], RFID[landmark_id, 1]], "-k") for i in range(N_PARTICLE): plt.plot(particles[i].x, particles[i].y, ".r") plt.plot(particles[i].lm[:, 0], particles[i].lm[:, 1], "xb") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.plot(xEst[0], xEst[1], "xk") plt.axis("equal") plt.grid(True) plt.pause(0.001)
1,344
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM2/fast_slam2.py
Particle.__init__
(self, N_LM)
37
46
def __init__(self, N_LM): self.w = 1.0 / N_PARTICLE self.x = 0.0 self.y = 0.0 self.yaw = 0.0 self.P = np.eye(3) # landmark x-y positions self.lm = np.zeros((N_LM, LM_SIZE)) # landmark position covariance self.lmP = np.zeros((N_LM * LM_SIZE, LM_SIZE))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM2/fast_slam2.py#L37-L46
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
97.046414
10
1
100
0
def __init__(self, N_LM): self.w = 1.0 / N_PARTICLE self.x = 0.0 self.y = 0.0 self.yaw = 0.0 self.P = np.eye(3) # landmark x-y positions self.lm = np.zeros((N_LM, LM_SIZE)) # landmark position covariance self.lmP = np.zeros((N_LM * LM_SIZE, LM_SIZE))
1,345
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
icp_matching
(previous_points, current_points)
return R, T
Iterative Closest Point matching - input previous_points: 2D or 3D points in the previous frame current_points: 2D or 3D points in the current frame - output R: Rotation matrix T: Translation vector
Iterative Closest Point matching - input previous_points: 2D or 3D points in the previous frame current_points: 2D or 3D points in the current frame - output R: Rotation matrix T: Translation vector
19
72
def icp_matching(previous_points, current_points): """ Iterative Closest Point matching - input previous_points: 2D or 3D points in the previous frame current_points: 2D or 3D points in the current frame - output R: Rotation matrix T: Translation vector """ H = None # homogeneous transformation matrix dError = np.inf preError = np.inf count = 0 if show_animation: fig = plt.figure() if previous_points.shape[0] == 3: fig.add_subplot(111, projection='3d') while dError >= EPS: count += 1 if show_animation: # pragma: no cover plot_points(previous_points, current_points, fig) plt.pause(0.1) indexes, error = nearest_neighbor_association(previous_points, current_points) Rt, Tt = svd_motion_estimation(previous_points[:, indexes], current_points) # update current points current_points = (Rt @ current_points) + Tt[:, np.newaxis] dError = preError - error print("Residual:", error) if dError < 0: # prevent matrix H changing, exit loop print("Not Converge...", preError, dError, count) break preError = error H = update_homogeneous_matrix(H, Rt, Tt) if dError <= EPS: print("Converge", error, dError, count) break elif MAX_ITER <= count: print("Not Converge...", error, dError, count) break R = np.array(H[0:-1, 0:-1]) T = np.array(H[0:-1, -1]) return R, T
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L19-L72
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46, 49, 50, 51, 52, 53 ]
92.156863
[ 17, 18, 19, 44, 45, 47, 48 ]
13.72549
false
80.701754
54
8
86.27451
7
def icp_matching(previous_points, current_points): H = None # homogeneous transformation matrix dError = np.inf preError = np.inf count = 0 if show_animation: fig = plt.figure() if previous_points.shape[0] == 3: fig.add_subplot(111, projection='3d') while dError >= EPS: count += 1 if show_animation: # pragma: no cover plot_points(previous_points, current_points, fig) plt.pause(0.1) indexes, error = nearest_neighbor_association(previous_points, current_points) Rt, Tt = svd_motion_estimation(previous_points[:, indexes], current_points) # update current points current_points = (Rt @ current_points) + Tt[:, np.newaxis] dError = preError - error print("Residual:", error) if dError < 0: # prevent matrix H changing, exit loop print("Not Converge...", preError, dError, count) break preError = error H = update_homogeneous_matrix(H, Rt, Tt) if dError <= EPS: print("Converge", error, dError, count) break elif MAX_ITER <= count: print("Not Converge...", error, dError, count) break R = np.array(H[0:-1, 0:-1]) T = np.array(H[0:-1, -1]) return R, T
1,346
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
update_homogeneous_matrix
(Hin, R, T)
75
87
def update_homogeneous_matrix(Hin, R, T): r_size = R.shape[0] H = np.zeros((r_size + 1, r_size + 1)) H[0:r_size, 0:r_size] = R H[0:r_size, r_size] = T H[r_size, r_size] = 1.0 if Hin is None: return H else: return Hin @ H
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L75-L87
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12 ]
92.307692
[]
0
false
80.701754
13
2
100
0
def update_homogeneous_matrix(Hin, R, T): r_size = R.shape[0] H = np.zeros((r_size + 1, r_size + 1)) H[0:r_size, 0:r_size] = R H[0:r_size, r_size] = T H[r_size, r_size] = 1.0 if Hin is None: return H else: return Hin @ H
1,347
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
nearest_neighbor_association
(previous_points, current_points)
return indexes, error
90
102
def nearest_neighbor_association(previous_points, current_points): # calc the sum of residual errors delta_points = previous_points - current_points d = np.linalg.norm(delta_points, axis=0) error = sum(d) # calc index with nearest neighbor assosiation d = np.linalg.norm(np.repeat(current_points, previous_points.shape[1], axis=1) - np.tile(previous_points, (1, current_points.shape[1])), axis=0) indexes = np.argmin(d.reshape(current_points.shape[1], previous_points.shape[1]), axis=1) return indexes, error
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L90-L102
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12 ]
92.307692
[]
0
false
80.701754
13
1
100
0
def nearest_neighbor_association(previous_points, current_points): # calc the sum of residual errors delta_points = previous_points - current_points d = np.linalg.norm(delta_points, axis=0) error = sum(d) # calc index with nearest neighbor assosiation d = np.linalg.norm(np.repeat(current_points, previous_points.shape[1], axis=1) - np.tile(previous_points, (1, current_points.shape[1])), axis=0) indexes = np.argmin(d.reshape(current_points.shape[1], previous_points.shape[1]), axis=1) return indexes, error
1,348
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
svd_motion_estimation
(previous_points, current_points)
return R, t
105
118
def svd_motion_estimation(previous_points, current_points): pm = np.mean(previous_points, axis=1) cm = np.mean(current_points, axis=1) p_shift = previous_points - pm[:, np.newaxis] c_shift = current_points - cm[:, np.newaxis] W = c_shift @ p_shift.T u, s, vh = np.linalg.svd(W) R = (u @ vh).T t = pm - (R @ cm) return R, t
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L105-L118
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
80.701754
14
1
100
0
def svd_motion_estimation(previous_points, current_points): pm = np.mean(previous_points, axis=1) cm = np.mean(current_points, axis=1) p_shift = previous_points - pm[:, np.newaxis] c_shift = current_points - cm[:, np.newaxis] W = c_shift @ p_shift.T u, s, vh = np.linalg.svd(W) R = (u @ vh).T t = pm - (R @ cm) return R, t
1,349
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
plot_points
(previous_points, current_points, figure)
121
140
def plot_points(previous_points, current_points, figure): # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) if previous_points.shape[0] == 3: plt.clf() axes = figure.add_subplot(111, projection='3d') axes.scatter(previous_points[0, :], previous_points[1, :], previous_points[2, :], c="r", marker=".") axes.scatter(current_points[0, :], current_points[1, :], current_points[2, :], c="b", marker=".") axes.scatter(0.0, 0.0, 0.0, c="r", marker="x") figure.canvas.draw() else: plt.cla() plt.plot(previous_points[0, :], previous_points[1, :], ".r") plt.plot(current_points[0, :], current_points[1, :], ".b") plt.plot(0.0, 0.0, "xr") plt.axis("equal")
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L121-L140
2
[ 0, 1 ]
10
[ 2, 5, 6, 7, 8, 10, 12, 13, 15, 16, 17, 18, 19 ]
65
false
80.701754
20
2
35
0
def plot_points(previous_points, current_points, figure): # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) if previous_points.shape[0] == 3: plt.clf() axes = figure.add_subplot(111, projection='3d') axes.scatter(previous_points[0, :], previous_points[1, :], previous_points[2, :], c="r", marker=".") axes.scatter(current_points[0, :], current_points[1, :], current_points[2, :], c="b", marker=".") axes.scatter(0.0, 0.0, 0.0, c="r", marker="x") figure.canvas.draw() else: plt.cla() plt.plot(previous_points[0, :], previous_points[1, :], ".r") plt.plot(current_points[0, :], current_points[1, :], ".b") plt.plot(0.0, 0.0, "xr") plt.axis("equal")
1,350
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
main
()
143
169
def main(): print(__file__ + " start!!") # simulation parameters nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, np.deg2rad(-10.0)] # movement [x[m],y[m],yaw[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points px = (np.random.rand(nPoint) - 0.5) * fieldLength py = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py)) # current points cx = [math.cos(motion[2]) * x - math.sin(motion[2]) * y + motion[0] for (x, y) in zip(px, py)] cy = [math.sin(motion[2]) * x + math.cos(motion[2]) * y + motion[1] for (x, y) in zip(px, py)] current_points = np.vstack((cx, cy)) R, T = icp_matching(previous_points, current_points) print("R:", R) print("T:", T)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L143-L169
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 24, 25, 26 ]
92.592593
[]
0
false
80.701754
27
4
100
0
def main(): print(__file__ + " start!!") # simulation parameters nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, np.deg2rad(-10.0)] # movement [x[m],y[m],yaw[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points px = (np.random.rand(nPoint) - 0.5) * fieldLength py = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py)) # current points cx = [math.cos(motion[2]) * x - math.sin(motion[2]) * y + motion[0] for (x, y) in zip(px, py)] cy = [math.sin(motion[2]) * x + math.cos(motion[2]) * y + motion[1] for (x, y) in zip(px, py)] current_points = np.vstack((cx, cy)) R, T = icp_matching(previous_points, current_points) print("R:", R) print("T:", T)
1,351
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/iterative_closest_point/iterative_closest_point.py
main_3d_points
()
172
200
def main_3d_points(): print(__file__ + " start!!") # simulation parameters for 3d point set nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, -5, np.deg2rad(-10.0)] # [x[m],y[m],z[m],roll[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points px = (np.random.rand(nPoint) - 0.5) * fieldLength py = (np.random.rand(nPoint) - 0.5) * fieldLength pz = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py, pz)) # current points cx = [math.cos(motion[3]) * x - math.sin(motion[3]) * z + motion[0] for (x, z) in zip(px, pz)] cy = [y + motion[1] for y in py] cz = [math.sin(motion[3]) * x + math.cos(motion[3]) * z + motion[2] for (x, z) in zip(px, pz)] current_points = np.vstack((cx, cy, cz)) R, T = icp_matching(previous_points, current_points) print("R:", R) print("T:", T)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/iterative_closest_point/iterative_closest_point.py#L172-L200
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 24, 25, 26, 27, 28 ]
93.103448
[]
0
false
80.701754
29
5
100
0
def main_3d_points(): print(__file__ + " start!!") # simulation parameters for 3d point set nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, -5, np.deg2rad(-10.0)] # [x[m],y[m],z[m],roll[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points px = (np.random.rand(nPoint) - 0.5) * fieldLength py = (np.random.rand(nPoint) - 0.5) * fieldLength pz = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py, pz)) # current points cx = [math.cos(motion[3]) * x - math.sin(motion[3]) * z + motion[0] for (x, z) in zip(px, pz)] cy = [y + motion[1] for y in py] cz = [math.sin(motion[3]) * x + math.cos(motion[3]) * z + motion[2] for (x, z) in zip(px, pz)] current_points = np.vstack((cx, cy, cz)) R, T = icp_matching(previous_points, current_points) print("R:", R) print("T:", T)
1,352
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
ekf_slam
(xEst, PEst, u, z)
return xEst, PEst
29
59
def ekf_slam(xEst, PEst, u, z): # Predict S = STATE_SIZE G, Fx = jacob_motion(xEst[0:S], u) xEst[0:S] = motion_model(xEst[0:S], u) PEst[0:S, 0:S] = G.T @ PEst[0:S, 0:S] @ G + Fx.T @ Cx @ Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation min_id = search_correspond_landmark_id(xEst, PEst, z[iz, 0:2]) nLM = calc_n_lm(xEst) if min_id == nLM: print("New LM") # Extend state and covariance matrix xAug = np.vstack((xEst, calc_landmark_position(xEst, z[iz, :]))) PAug = np.vstack((np.hstack((PEst, np.zeros((len(xEst), LM_SIZE)))), np.hstack((np.zeros((LM_SIZE, len(xEst))), initP)))) xEst = xAug PEst = PAug lm = get_landmark_position_from_state(xEst, min_id) y, S, H = calc_innovation(lm, xEst, PEst, z[iz, 0:2], min_id) K = (PEst @ H.T) @ np.linalg.inv(S) xEst = xEst + (K @ y) PEst = (np.eye(len(xEst)) - (K @ H)) @ PEst xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L29-L59
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 ]
96.774194
[]
0
false
99.236641
31
3
100
0
def ekf_slam(xEst, PEst, u, z): # Predict S = STATE_SIZE G, Fx = jacob_motion(xEst[0:S], u) xEst[0:S] = motion_model(xEst[0:S], u) PEst[0:S, 0:S] = G.T @ PEst[0:S, 0:S] @ G + Fx.T @ Cx @ Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation min_id = search_correspond_landmark_id(xEst, PEst, z[iz, 0:2]) nLM = calc_n_lm(xEst) if min_id == nLM: print("New LM") # Extend state and covariance matrix xAug = np.vstack((xEst, calc_landmark_position(xEst, z[iz, :]))) PAug = np.vstack((np.hstack((PEst, np.zeros((len(xEst), LM_SIZE)))), np.hstack((np.zeros((LM_SIZE, len(xEst))), initP)))) xEst = xAug PEst = PAug lm = get_landmark_position_from_state(xEst, min_id) y, S, H = calc_innovation(lm, xEst, PEst, z[iz, 0:2], min_id) K = (PEst @ H.T) @ np.linalg.inv(S) xEst = xEst + (K @ y) PEst = (np.eye(len(xEst)) - (K @ H)) @ PEst xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst
1,353
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
calc_input
()
return u
62
66
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/SLAM/EKFSLAM/ekf_slam.py#L62-L66
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
99.236641
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
1,354
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
observation
(xTrue, xd, u, RFID)
return xTrue, z, xd, ud
69
93
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_n = angle + np.random.randn() * Q_sim[1, 1] ** 0.5 # add noise zi = np.array([dn, angle_n, i]) z = np.vstack((z, zi)) # add noise to input ud = np.array([[ u[0, 0] + np.random.randn() * R_sim[0, 0] ** 0.5, u[1, 0] + np.random.randn() * R_sim[1, 1] ** 0.5]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L69-L93
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24 ]
92
[]
0
false
99.236641
25
3
100
0
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_n = angle + np.random.randn() * Q_sim[1, 1] ** 0.5 # add noise zi = np.array([dn, angle_n, i]) z = np.vstack((z, zi)) # add noise to input ud = np.array([[ u[0, 0] + np.random.randn() * R_sim[0, 0] ** 0.5, u[1, 0] + np.random.randn() * R_sim[1, 1] ** 0.5]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud
1,355
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
motion_model
(x, u)
return x
96
106
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L96-L106
2
[ 0, 1, 4, 5, 8, 9, 10 ]
63.636364
[]
0
false
99.236641
11
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
1,356
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
calc_n_lm
(x)
return n
109
111
def calc_n_lm(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L109-L111
2
[ 0, 1, 2 ]
100
[]
0
true
99.236641
3
1
100
0
def calc_n_lm(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
1,357
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
jacob_motion
(x, u)
return G, Fx,
114
124
def jacob_motion(x, u): Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_lm(x))))) jF = np.array([[0.0, 0.0, -DT * u[0, 0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0, 0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]], dtype=float) G = np.eye(STATE_SIZE) + Fx.T @ jF @ Fx return G, Fx,
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L114-L124
2
[ 0, 1, 3, 4, 7, 8, 9, 10 ]
72.727273
[]
0
false
99.236641
11
1
100
0
def jacob_motion(x, u): Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_lm(x))))) jF = np.array([[0.0, 0.0, -DT * u[0, 0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0, 0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]], dtype=float) G = np.eye(STATE_SIZE) + Fx.T @ jF @ Fx return G, Fx,
1,358
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
calc_landmark_position
(x, z)
return zp
127
133
def calc_landmark_position(x, z): zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) return zp
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L127-L133
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
99.236641
7
1
100
0
def calc_landmark_position(x, z): zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) return zp
1,359
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
get_landmark_position_from_state
(x, ind)
return lm
136
139
def get_landmark_position_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L136-L139
2
[ 0, 1, 2, 3 ]
100
[]
0
true
99.236641
4
1
100
0
def get_landmark_position_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
1,360
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
search_correspond_landmark_id
(xAug, PAug, zi)
return min_id
Landmark association with Mahalanobis distance
Landmark association with Mahalanobis distance
142
160
def search_correspond_landmark_id(xAug, PAug, zi): """ Landmark association with Mahalanobis distance """ nLM = calc_n_lm(xAug) min_dist = [] for i in range(nLM): lm = get_landmark_position_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) min_dist.append(y.T @ np.linalg.inv(S) @ y) min_dist.append(M_DIST_TH) # new landmark min_id = min_dist.index(min(min_dist)) return min_id
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L142-L160
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]
100
[]
0
true
99.236641
19
2
100
1
def search_correspond_landmark_id(xAug, PAug, zi): nLM = calc_n_lm(xAug) min_dist = [] for i in range(nLM): lm = get_landmark_position_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) min_dist.append(y.T @ np.linalg.inv(S) @ y) min_dist.append(M_DIST_TH) # new landmark min_id = min_dist.index(min(min_dist)) return min_id
1,361
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
calc_innovation
(lm, xEst, PEst, z, LMid)
return y, S, H
163
173
def calc_innovation(lm, xEst, PEst, z, LMid): delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] z_angle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(z_angle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacob_h(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L163-L173
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
99.236641
11
1
100
0
def calc_innovation(lm, xEst, PEst, z, LMid): delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] z_angle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(z_angle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacob_h(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H
1,362
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
jacob_h
(q, delta, x, i)
return H
176
191
def jacob_h(q, delta, x, i): sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - q, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_lm(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np.zeros((2, 3)), np.zeros((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L176-L191
2
[ 0, 1, 2, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15 ]
87.5
[]
0
false
99.236641
16
1
100
0
def jacob_h(q, delta, x, i): sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - q, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_lm(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np.zeros((2, 3)), np.zeros((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H
1,363
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
194
195
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L194-L195
2
[ 0, 1 ]
100
[]
0
true
99.236641
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
1,364
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/EKFSLAM/ekf_slam.py
main
()
198
259
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros((STATE_SIZE, 1)) PEst = np.eye(STATE_SIZE) xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue while SIM_TIME >= time: time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) xEst, PEst = ekf_slam(xEst, PEst, ud, z) x_state = xEst[0:STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") plt.plot(xEst[0], xEst[1], ".r") # plot landmark for i in range(calc_n_lm(xEst)): plt.plot(xEst[STATE_SIZE + i * 2], xEst[STATE_SIZE + i * 2 + 1], "xg") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.axis("equal") plt.grid(True) plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/EKFSLAM/ekf_slam.py#L198-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 ]
69.387755
[]
0
false
99.236641
62
4
100
0
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros((STATE_SIZE, 1)) PEst = np.eye(STATE_SIZE) xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue while SIM_TIME >= time: time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) xEst, PEst = ekf_slam(xEst, PEst, ud, z) x_state = xEst[0:STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") plt.plot(xEst[0], xEst[1], ".r") # plot landmark for i in range(calc_n_lm(xEst)): plt.plot(xEst[STATE_SIZE + i * 2], xEst[STATE_SIZE + i * 2 + 1], "xg") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.axis("equal") plt.grid(True) plt.pause(0.001)
1,365
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
cal_observation_sigma
()
return sigma
60
66
def cal_observation_sigma(): sigma = np.zeros((3, 3)) sigma[0, 0] = C_SIGMA1 ** 2 sigma[1, 1] = C_SIGMA2 ** 2 sigma[2, 2] = C_SIGMA3 ** 2 return sigma
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L60-L66
2
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
98.901099
7
1
100
0
def cal_observation_sigma(): sigma = np.zeros((3, 3)) sigma[0, 0] = C_SIGMA1 ** 2 sigma[1, 1] = C_SIGMA2 ** 2 sigma[2, 2] = C_SIGMA3 ** 2 return sigma
1,366
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
calc_3d_rotational_matrix
(angle)
return Rot.from_euler('z', angle).as_matrix()
69
70
def calc_3d_rotational_matrix(angle): return Rot.from_euler('z', angle).as_matrix()
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L69-L70
2
[ 0, 1 ]
100
[]
0
true
98.901099
2
1
100
0
def calc_3d_rotational_matrix(angle): return Rot.from_euler('z', angle).as_matrix()
1,367
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
calc_edge
(x1, y1, yaw1, x2, y2, yaw2, d1, angle1, d2, angle2, t1, t2)
return edge
73
101
def calc_edge(x1, y1, yaw1, x2, y2, yaw2, d1, angle1, d2, angle2, t1, t2): edge = Edge() tangle1 = pi_2_pi(yaw1 + angle1) tangle2 = pi_2_pi(yaw2 + angle2) tmp1 = d1 * math.cos(tangle1) tmp2 = d2 * math.cos(tangle2) tmp3 = d1 * math.sin(tangle1) tmp4 = d2 * math.sin(tangle2) edge.e[0, 0] = x2 - x1 - tmp1 + tmp2 edge.e[1, 0] = y2 - y1 - tmp3 + tmp4 edge.e[2, 0] = 0 Rt1 = calc_3d_rotational_matrix(tangle1) Rt2 = calc_3d_rotational_matrix(tangle2) sig1 = cal_observation_sigma() sig2 = cal_observation_sigma() edge.omega = np.linalg.inv(Rt1 @ sig1 @ Rt1.T + Rt2 @ sig2 @ Rt2.T) edge.d1, edge.d2 = d1, d2 edge.yaw1, edge.yaw2 = yaw1, yaw2 edge.angle1, edge.angle2 = angle1, angle2 edge.id1, edge.id2 = t1, t2 return edge
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L73-L101
2
[ 0, 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 ]
96.551724
[]
0
false
98.901099
29
1
100
0
def calc_edge(x1, y1, yaw1, x2, y2, yaw2, d1, angle1, d2, angle2, t1, t2): edge = Edge() tangle1 = pi_2_pi(yaw1 + angle1) tangle2 = pi_2_pi(yaw2 + angle2) tmp1 = d1 * math.cos(tangle1) tmp2 = d2 * math.cos(tangle2) tmp3 = d1 * math.sin(tangle1) tmp4 = d2 * math.sin(tangle2) edge.e[0, 0] = x2 - x1 - tmp1 + tmp2 edge.e[1, 0] = y2 - y1 - tmp3 + tmp4 edge.e[2, 0] = 0 Rt1 = calc_3d_rotational_matrix(tangle1) Rt2 = calc_3d_rotational_matrix(tangle2) sig1 = cal_observation_sigma() sig2 = cal_observation_sigma() edge.omega = np.linalg.inv(Rt1 @ sig1 @ Rt1.T + Rt2 @ sig2 @ Rt2.T) edge.d1, edge.d2 = d1, d2 edge.yaw1, edge.yaw2 = yaw1, yaw2 edge.angle1, edge.angle2 = angle1, angle2 edge.id1, edge.id2 = t1, t2 return edge
1,368
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
calc_edges
(x_list, z_list)
return edges
104
131
def calc_edges(x_list, z_list): edges = [] cost = 0.0 z_ids = list(itertools.combinations(range(len(z_list)), 2)) for (t1, t2) in z_ids: x1, y1, yaw1 = x_list[0, t1], x_list[1, t1], x_list[2, t1] x2, y2, yaw2 = x_list[0, t2], x_list[1, t2], x_list[2, t2] if z_list[t1] is None or z_list[t2] is None: continue # No observation for iz1 in range(len(z_list[t1][:, 0])): for iz2 in range(len(z_list[t2][:, 0])): if z_list[t1][iz1, 3] == z_list[t2][iz2, 3]: d1 = z_list[t1][iz1, 0] angle1, phi1 = z_list[t1][iz1, 1], z_list[t1][iz1, 2] d2 = z_list[t2][iz2, 0] angle2, phi2 = z_list[t2][iz2, 1], z_list[t2][iz2, 2] edge = calc_edge(x1, y1, yaw1, x2, y2, yaw2, d1, angle1, d2, angle2, t1, t2) edges.append(edge) cost += (edge.e.T @ edge.omega @ edge.e)[0, 0] print("cost:", cost, ",n_edge:", len(edges)) return edges
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L104-L131
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27 ]
92.857143
[ 10 ]
3.571429
false
98.901099
28
7
96.428571
0
def calc_edges(x_list, z_list): edges = [] cost = 0.0 z_ids = list(itertools.combinations(range(len(z_list)), 2)) for (t1, t2) in z_ids: x1, y1, yaw1 = x_list[0, t1], x_list[1, t1], x_list[2, t1] x2, y2, yaw2 = x_list[0, t2], x_list[1, t2], x_list[2, t2] if z_list[t1] is None or z_list[t2] is None: continue # No observation for iz1 in range(len(z_list[t1][:, 0])): for iz2 in range(len(z_list[t2][:, 0])): if z_list[t1][iz1, 3] == z_list[t2][iz2, 3]: d1 = z_list[t1][iz1, 0] angle1, phi1 = z_list[t1][iz1, 1], z_list[t1][iz1, 2] d2 = z_list[t2][iz2, 0] angle2, phi2 = z_list[t2][iz2, 1], z_list[t2][iz2, 2] edge = calc_edge(x1, y1, yaw1, x2, y2, yaw2, d1, angle1, d2, angle2, t1, t2) edges.append(edge) cost += (edge.e.T @ edge.omega @ edge.e)[0, 0] print("cost:", cost, ",n_edge:", len(edges)) return edges
1,369
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
calc_jacobian
(edge)
return A, B
134
145
def calc_jacobian(edge): t1 = edge.yaw1 + edge.angle1 A = np.array([[-1.0, 0, edge.d1 * math.sin(t1)], [0, -1.0, -edge.d1 * math.cos(t1)], [0, 0, 0]]) t2 = edge.yaw2 + edge.angle2 B = np.array([[1.0, 0, -edge.d2 * math.sin(t2)], [0, 1.0, edge.d2 * math.cos(t2)], [0, 0, 0]]) return A, B
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L134-L145
2
[ 0, 1, 2, 5, 6, 7, 10, 11 ]
66.666667
[]
0
false
98.901099
12
1
100
0
def calc_jacobian(edge): t1 = edge.yaw1 + edge.angle1 A = np.array([[-1.0, 0, edge.d1 * math.sin(t1)], [0, -1.0, -edge.d1 * math.cos(t1)], [0, 0, 0]]) t2 = edge.yaw2 + edge.angle2 B = np.array([[1.0, 0, -edge.d2 * math.sin(t2)], [0, 1.0, edge.d2 * math.cos(t2)], [0, 0, 0]]) return A, B
1,370
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
fill_H_and_b
(H, b, edge)
return H, b
148
162
def fill_H_and_b(H, b, edge): A, B = calc_jacobian(edge) id1 = edge.id1 * STATE_SIZE id2 = edge.id2 * STATE_SIZE H[id1:id1 + STATE_SIZE, id1:id1 + STATE_SIZE] += A.T @ edge.omega @ A H[id1:id1 + STATE_SIZE, id2:id2 + STATE_SIZE] += A.T @ edge.omega @ B H[id2:id2 + STATE_SIZE, id1:id1 + STATE_SIZE] += B.T @ edge.omega @ A H[id2:id2 + STATE_SIZE, id2:id2 + STATE_SIZE] += B.T @ edge.omega @ B b[id1:id1 + STATE_SIZE] += (A.T @ edge.omega @ edge.e) b[id2:id2 + STATE_SIZE] += (B.T @ edge.omega @ edge.e) return H, b
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L148-L162
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
98.901099
15
1
100
0
def fill_H_and_b(H, b, edge): A, B = calc_jacobian(edge) id1 = edge.id1 * STATE_SIZE id2 = edge.id2 * STATE_SIZE H[id1:id1 + STATE_SIZE, id1:id1 + STATE_SIZE] += A.T @ edge.omega @ A H[id1:id1 + STATE_SIZE, id2:id2 + STATE_SIZE] += A.T @ edge.omega @ B H[id2:id2 + STATE_SIZE, id1:id1 + STATE_SIZE] += B.T @ edge.omega @ A H[id2:id2 + STATE_SIZE, id2:id2 + STATE_SIZE] += B.T @ edge.omega @ B b[id1:id1 + STATE_SIZE] += (A.T @ edge.omega @ edge.e) b[id2:id2 + STATE_SIZE] += (B.T @ edge.omega @ edge.e) return H, b
1,371
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
graph_based_slam
(x_init, hz)
return x_opt
165
196
def graph_based_slam(x_init, hz): print("start graph based slam") z_list = copy.deepcopy(hz) x_opt = copy.deepcopy(x_init) nt = x_opt.shape[1] n = nt * STATE_SIZE for itr in range(MAX_ITR): edges = calc_edges(x_opt, z_list) H = np.zeros((n, n)) b = np.zeros((n, 1)) for edge in edges: H, b = fill_H_and_b(H, b, edge) # to fix origin H[0:STATE_SIZE, 0:STATE_SIZE] += np.identity(STATE_SIZE) dx = - np.linalg.inv(H) @ b for i in range(nt): x_opt[0:3, i] += dx[i * 3:i * 3 + 3, 0] diff = dx.T @ dx print("iteration: %d, diff: %f" % (itr + 1, diff)) if diff < 1.0e-5: break return x_opt
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L165-L196
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 ]
100
[]
0
true
98.901099
32
5
100
0
def graph_based_slam(x_init, hz): print("start graph based slam") z_list = copy.deepcopy(hz) x_opt = copy.deepcopy(x_init) nt = x_opt.shape[1] n = nt * STATE_SIZE for itr in range(MAX_ITR): edges = calc_edges(x_opt, z_list) H = np.zeros((n, n)) b = np.zeros((n, 1)) for edge in edges: H, b = fill_H_and_b(H, b, edge) # to fix origin H[0:STATE_SIZE, 0:STATE_SIZE] += np.identity(STATE_SIZE) dx = - np.linalg.inv(H) @ b for i in range(nt): x_opt[0:3, i] += dx[i * 3:i * 3 + 3, 0] diff = dx.T @ dx print("iteration: %d, diff: %f" % (itr + 1, diff)) if diff < 1.0e-5: break return x_opt
1,372
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
calc_input
()
return u
199
203
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/SLAM/GraphBasedSLAM/graph_based_slam.py#L199-L203
2
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
98.901099
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
1,373
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
observation
(xTrue, xd, u, RFID)
return xTrue, z, xd, ud
206
234
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 4)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx)) - xTrue[2, 0] phi = pi_2_pi(math.atan2(dy, dx)) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] # add noise angle_noise = np.random.randn() * Q_sim[1, 1] angle += angle_noise phi += angle_noise zi = np.array([dn, angle, phi, i]) z = np.vstack((z, zi)) # add noise to input ud1 = u[0, 0] + np.random.randn() * R_sim[0, 0] ud2 = u[1, 0] + np.random.randn() * R_sim[1, 1] ud = np.array([[ud1, ud2]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L206-L234
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
98.901099
29
3
100
0
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 4)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx)) - xTrue[2, 0] phi = pi_2_pi(math.atan2(dy, dx)) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] # add noise angle_noise = np.random.randn() * Q_sim[1, 1] angle += angle_noise phi += angle_noise zi = np.array([dn, angle, phi, i]) z = np.vstack((z, zi)) # add noise to input ud1 = u[0, 0] + np.random.randn() * R_sim[0, 0] ud2 = u[1, 0] + np.random.randn() * R_sim[1, 1] ud = np.array([[ud1, ud2]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud
1,374
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
motion_model
(x, u)
return x
237
248
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L237-L248
2
[ 0, 1, 4, 5, 8, 9, 10, 11 ]
66.666667
[]
0
false
98.901099
12
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u return x
1,375
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
251
252
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L251-L252
2
[ 0, 1 ]
100
[]
0
true
98.901099
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
1,376
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
main
()
255
317
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y, yaw] RFID = np.array([[10.0, -2.0, 0.0], [15.0, 10.0, 0.0], [3.0, 15.0, 0.0], [-5.0, 20.0, 0.0], [-5.0, 5.0, 0.0] ]) # State Vector [x y yaw v]' xTrue = np.zeros((STATE_SIZE, 1)) xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxTrue = [] hxDR = [] hz = [] d_time = 0.0 init = False while SIM_TIME >= time: if not init: hxTrue = xTrue hxDR = xTrue init = True else: hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) time += DT d_time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) hz.append(z) if d_time >= show_graph_d_time: x_opt = graph_based_slam(hxDR, hz) d_time = 0.0 if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") plt.plot(hxTrue[0, :].flatten(), hxTrue[1, :].flatten(), "-b") plt.plot(hxDR[0, :].flatten(), hxDR[1, :].flatten(), "-k") plt.plot(x_opt[0, :].flatten(), x_opt[1, :].flatten(), "-r") plt.axis("equal") plt.grid(True) plt.title("Time" + str(time)[0:5]) plt.pause(1.0)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L255-L317
2
[ 0, 1, 2, 3, 4, 5, 6, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44 ]
73.076923
[]
0
false
98.901099
63
5
100
0
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y, yaw] RFID = np.array([[10.0, -2.0, 0.0], [15.0, 10.0, 0.0], [3.0, 15.0, 0.0], [-5.0, 20.0, 0.0], [-5.0, 5.0, 0.0] ]) # State Vector [x y yaw v]' xTrue = np.zeros((STATE_SIZE, 1)) xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxTrue = [] hxDR = [] hz = [] d_time = 0.0 init = False while SIM_TIME >= time: if not init: hxTrue = xTrue hxDR = xTrue init = True else: hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) time += DT d_time += DT u = calc_input() xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) hz.append(z) if d_time >= show_graph_d_time: x_opt = graph_based_slam(hxDR, hz) d_time = 0.0 if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") plt.plot(hxTrue[0, :].flatten(), hxTrue[1, :].flatten(), "-b") plt.plot(hxDR[0, :].flatten(), hxDR[1, :].flatten(), "-k") plt.plot(x_opt[0, :].flatten(), x_opt[1, :].flatten(), "-r") plt.axis("equal") plt.grid(True) plt.title("Time" + str(time)[0:5]) plt.pause(1.0)
1,377
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/GraphBasedSLAM/graph_based_slam.py
Edge.__init__
(self)
47
57
def __init__(self): self.e = np.zeros((3, 1)) self.omega = np.zeros((3, 3)) # information matrix self.d1 = 0.0 self.d2 = 0.0 self.yaw1 = 0.0 self.yaw2 = 0.0 self.angle1 = 0.0 self.angle2 = 0.0 self.id1 = 0 self.id2 = 0
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/GraphBasedSLAM/graph_based_slam.py#L47-L57
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
98.901099
11
1
100
0
def __init__(self): self.e = np.zeros((3, 1)) self.omega = np.zeros((3, 3)) # information matrix self.d1 = 0.0 self.d2 = 0.0 self.yaw1 = 0.0 self.yaw2 = 0.0 self.angle1 = 0.0 self.angle2 = 0.0 self.id1 = 0 self.id2 = 0
1,378
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
fast_slam1
(particles, u, z)
return particles
48
55
def fast_slam1(particles, u, z): particles = predict_particles(particles, u) particles = update_with_observation(particles, z) particles = resampling(particles) return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L48-L55
2
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
96.330275
8
1
100
0
def fast_slam1(particles, u, z): particles = predict_particles(particles, u) particles = update_with_observation(particles, z) particles = resampling(particles) return particles
1,414
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
normalize_weight
(particles)
return particles
58
70
def normalize_weight(particles): sum_w = sum([p.w for p in particles]) try: for i in range(N_PARTICLE): particles[i].w /= sum_w except ZeroDivisionError: for i in range(N_PARTICLE): particles[i].w = 1.0 / N_PARTICLE return particles return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L58-L70
2
[ 0, 1, 2, 3, 4, 5, 11, 12 ]
61.538462
[ 6, 7, 8, 10 ]
30.769231
false
96.330275
13
5
69.230769
0
def normalize_weight(particles): sum_w = sum([p.w for p in particles]) try: for i in range(N_PARTICLE): particles[i].w /= sum_w except ZeroDivisionError: for i in range(N_PARTICLE): particles[i].w = 1.0 / N_PARTICLE return particles return particles
1,415
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
calc_final_state
(particles)
return xEst
73
86
def calc_final_state(particles): xEst = np.zeros((STATE_SIZE, 1)) particles = normalize_weight(particles) for i in range(N_PARTICLE): xEst[0, 0] += particles[i].w * particles[i].x xEst[1, 0] += particles[i].w * particles[i].y xEst[2, 0] += particles[i].w * particles[i].yaw xEst[2, 0] = pi_2_pi(xEst[2, 0]) # print(xEst) return xEst
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L73-L86
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
96.330275
14
2
100
0
def calc_final_state(particles): xEst = np.zeros((STATE_SIZE, 1)) particles = normalize_weight(particles) for i in range(N_PARTICLE): xEst[0, 0] += particles[i].w * particles[i].x xEst[1, 0] += particles[i].w * particles[i].y xEst[2, 0] += particles[i].w * particles[i].yaw xEst[2, 0] = pi_2_pi(xEst[2, 0]) # print(xEst) return xEst
1,416
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
predict_particles
(particles, u)
return particles
89
101
def predict_particles(particles, u): for i in range(N_PARTICLE): px = np.zeros((STATE_SIZE, 1)) px[0, 0] = particles[i].x px[1, 0] = particles[i].y px[2, 0] = particles[i].yaw ud = u + (np.random.randn(1, 2) @ R ** 0.5).T # add noise px = motion_model(px, ud) particles[i].x = px[0, 0] particles[i].y = px[1, 0] particles[i].yaw = px[2, 0] return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L89-L101
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
96.330275
13
2
100
0
def predict_particles(particles, u): for i in range(N_PARTICLE): px = np.zeros((STATE_SIZE, 1)) px[0, 0] = particles[i].x px[1, 0] = particles[i].y px[2, 0] = particles[i].yaw ud = u + (np.random.randn(1, 2) @ R ** 0.5).T # add noise px = motion_model(px, ud) particles[i].x = px[0, 0] particles[i].y = px[1, 0] particles[i].yaw = px[2, 0] return particles
1,417
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
add_new_landmark
(particle, z, Q_cov)
return particle
104
125
def add_new_landmark(particle, z, Q_cov): r = z[0] b = z[1] lm_id = int(z[2]) s = math.sin(pi_2_pi(particle.yaw + b)) c = math.cos(pi_2_pi(particle.yaw + b)) particle.lm[lm_id, 0] = particle.x + r * c particle.lm[lm_id, 1] = particle.y + r * s # covariance dx = r * c dy = r * s d2 = dx**2 + dy**2 d = math.sqrt(d2) Gz = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) particle.lmP[2 * lm_id:2 * lm_id + 2] = np.linalg.inv( Gz) @ Q_cov @ np.linalg.inv(Gz.T) return particle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L104-L125
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21 ]
90.909091
[]
0
false
96.330275
22
1
100
0
def add_new_landmark(particle, z, Q_cov): r = z[0] b = z[1] lm_id = int(z[2]) s = math.sin(pi_2_pi(particle.yaw + b)) c = math.cos(pi_2_pi(particle.yaw + b)) particle.lm[lm_id, 0] = particle.x + r * c particle.lm[lm_id, 1] = particle.y + r * s # covariance dx = r * c dy = r * s d2 = dx**2 + dy**2 d = math.sqrt(d2) Gz = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) particle.lmP[2 * lm_id:2 * lm_id + 2] = np.linalg.inv( Gz) @ Q_cov @ np.linalg.inv(Gz.T) return particle
1,418
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
compute_jacobians
(particle, xf, Pf, Q_cov)
return zp, Hv, Hf, Sf
128
145
def compute_jacobians(particle, xf, Pf, Q_cov): dx = xf[0, 0] - particle.x dy = xf[1, 0] - particle.y d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) zp = np.array( [d, pi_2_pi(math.atan2(dy, dx) - particle.yaw)]).reshape(2, 1) Hv = np.array([[-dx / d, -dy / d, 0.0], [dy / d2, -dx / d2, -1.0]]) Hf = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) Sf = Hf @ Pf @ Hf.T + Q_cov return zp, Hv, Hf, Sf
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L128-L145
2
[ 0, 1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17 ]
83.333333
[]
0
false
96.330275
18
1
100
0
def compute_jacobians(particle, xf, Pf, Q_cov): dx = xf[0, 0] - particle.x dy = xf[1, 0] - particle.y d2 = dx ** 2 + dy ** 2 d = math.sqrt(d2) zp = np.array( [d, pi_2_pi(math.atan2(dy, dx) - particle.yaw)]).reshape(2, 1) Hv = np.array([[-dx / d, -dy / d, 0.0], [dy / d2, -dx / d2, -1.0]]) Hf = np.array([[dx / d, dy / d], [-dy / d2, dx / d2]]) Sf = Hf @ Pf @ Hf.T + Q_cov return zp, Hv, Hf, Sf
1,419
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
update_kf_with_cholesky
(xf, Pf, v, Q_cov, Hf)
return x, P
148
161
def update_kf_with_cholesky(xf, Pf, v, Q_cov, Hf): PHt = Pf @ Hf.T S = Hf @ PHt + Q_cov S = (S + S.T) * 0.5 s_chol = np.linalg.cholesky(S).T s_chol_inv = np.linalg.inv(s_chol) W1 = PHt @ s_chol_inv W = W1 @ s_chol_inv.T x = xf + W @ v P = Pf - W1 @ W1.T return x, P
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L148-L161
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
96.330275
14
1
100
0
def update_kf_with_cholesky(xf, Pf, v, Q_cov, Hf): PHt = Pf @ Hf.T S = Hf @ PHt + Q_cov S = (S + S.T) * 0.5 s_chol = np.linalg.cholesky(S).T s_chol_inv = np.linalg.inv(s_chol) W1 = PHt @ s_chol_inv W = W1 @ s_chol_inv.T x = xf + W @ v P = Pf - W1 @ W1.T return x, P
1,420
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
update_landmark
(particle, z, Q_cov)
return particle
164
179
def update_landmark(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2, :]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) xf, Pf = update_kf_with_cholesky(xf, Pf, dz, Q_cov, Hf) particle.lm[lm_id, :] = xf.T particle.lmP[2 * lm_id:2 * lm_id + 2, :] = Pf return particle
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L164-L179
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
96.330275
16
1
100
0
def update_landmark(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2, :]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q) dz = z[0:2].reshape(2, 1) - zp dz[1, 0] = pi_2_pi(dz[1, 0]) xf, Pf = update_kf_with_cholesky(xf, Pf, dz, Q_cov, Hf) particle.lm[lm_id, :] = xf.T particle.lmP[2 * lm_id:2 * lm_id + 2, :] = Pf return particle
1,421
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
compute_weight
(particle, z, Q_cov)
return w
182
202
def compute_weight(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dx = z[0:2].reshape(2, 1) - zp dx[1, 0] = pi_2_pi(dx[1, 0]) try: invS = np.linalg.inv(Sf) except np.linalg.linalg.LinAlgError: print("singular") return 1.0 num = math.exp(-0.5 * dx.T @ invS @ dx) den = 2.0 * math.pi * math.sqrt(np.linalg.det(Sf)) w = num / den return w
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L182-L202
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 19, 20 ]
85.714286
[ 11, 12, 13 ]
14.285714
false
96.330275
21
2
85.714286
0
def compute_weight(particle, z, Q_cov): lm_id = int(z[2]) xf = np.array(particle.lm[lm_id, :]).reshape(2, 1) Pf = np.array(particle.lmP[2 * lm_id:2 * lm_id + 2]) zp, Hv, Hf, Sf = compute_jacobians(particle, xf, Pf, Q_cov) dx = z[0:2].reshape(2, 1) - zp dx[1, 0] = pi_2_pi(dx[1, 0]) try: invS = np.linalg.inv(Sf) except np.linalg.linalg.LinAlgError: print("singular") return 1.0 num = math.exp(-0.5 * dx.T @ invS @ dx) den = 2.0 * math.pi * math.sqrt(np.linalg.det(Sf)) w = num / den return w
1,422
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
update_with_observation
(particles, z)
return particles
205
220
def update_with_observation(particles, z): for iz in range(len(z[0, :])): landmark_id = int(z[2, iz]) for ip in range(N_PARTICLE): # new landmark if abs(particles[ip].lm[landmark_id, 0]) <= 0.01: particles[ip] = add_new_landmark(particles[ip], z[:, iz], Q) # known landmark else: w = compute_weight(particles[ip], z[:, iz], Q) particles[ip].w *= w particles[ip] = update_landmark(particles[ip], z[:, iz], Q) return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L205-L220
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15 ]
93.75
[]
0
false
96.330275
16
4
100
0
def update_with_observation(particles, z): for iz in range(len(z[0, :])): landmark_id = int(z[2, iz]) for ip in range(N_PARTICLE): # new landmark if abs(particles[ip].lm[landmark_id, 0]) <= 0.01: particles[ip] = add_new_landmark(particles[ip], z[:, iz], Q) # known landmark else: w = compute_weight(particles[ip], z[:, iz], Q) particles[ip].w *= w particles[ip] = update_landmark(particles[ip], z[:, iz], Q) return particles
1,423
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
resampling
(particles)
return particles
low variance re-sampling
low variance re-sampling
223
261
def resampling(particles): """ low variance re-sampling """ particles = normalize_weight(particles) pw = [] for i in range(N_PARTICLE): pw.append(particles[i].w) pw = np.array(pw) n_eff = 1.0 / (pw @ pw.T) # Effective particle number # print(n_eff) if n_eff < NTH: # resampling w_cum = np.cumsum(pw) base = np.cumsum(pw * 0.0 + 1 / N_PARTICLE) - 1 / N_PARTICLE resample_id = base + np.random.rand(base.shape[0]) / N_PARTICLE inds = [] ind = 0 for ip in range(N_PARTICLE): while (ind < w_cum.shape[0] - 1) \ and (resample_id[ip] > w_cum[ind]): ind += 1 inds.append(ind) tmp_particles = particles[:] for i in range(len(inds)): particles[i].x = tmp_particles[inds[i]].x particles[i].y = tmp_particles[inds[i]].y particles[i].yaw = tmp_particles[inds[i]].yaw particles[i].lm = tmp_particles[inds[i]].lm[:, :] particles[i].lmP = tmp_particles[inds[i]].lmP[:, :] particles[i].w = 1.0 / N_PARTICLE return particles
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L223-L261
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 ]
100
[]
0
true
96.330275
39
7
100
1
def resampling(particles): particles = normalize_weight(particles) pw = [] for i in range(N_PARTICLE): pw.append(particles[i].w) pw = np.array(pw) n_eff = 1.0 / (pw @ pw.T) # Effective particle number # print(n_eff) if n_eff < NTH: # resampling w_cum = np.cumsum(pw) base = np.cumsum(pw * 0.0 + 1 / N_PARTICLE) - 1 / N_PARTICLE resample_id = base + np.random.rand(base.shape[0]) / N_PARTICLE inds = [] ind = 0 for ip in range(N_PARTICLE): while (ind < w_cum.shape[0] - 1) \ and (resample_id[ip] > w_cum[ind]): ind += 1 inds.append(ind) tmp_particles = particles[:] for i in range(len(inds)): particles[i].x = tmp_particles[inds[i]].x particles[i].y = tmp_particles[inds[i]].y particles[i].yaw = tmp_particles[inds[i]].yaw particles[i].lm = tmp_particles[inds[i]].lm[:, :] particles[i].lmP = tmp_particles[inds[i]].lmP[:, :] particles[i].w = 1.0 / N_PARTICLE return particles
1,424
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
calc_input
(time)
return u
264
274
def calc_input(time): if time <= 3.0: # wait at first v = 0.0 yaw_rate = 0.0 else: v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([v, yaw_rate]).reshape(2, 1) return u
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L264-L274
2
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10 ]
90.909091
[]
0
false
96.330275
11
2
100
0
def calc_input(time): if time <= 3.0: # wait at first v = 0.0 yaw_rate = 0.0 else: v = 1.0 # [m/s] yaw_rate = 0.1 # [rad/s] u = np.array([v, yaw_rate]).reshape(2, 1) return u
1,425
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
observation
(xTrue, xd, u, rfid)
return xTrue, z, xd, ud
277
304
def observation(xTrue, xd, u, rfid): # calc true state xTrue = motion_model(xTrue, u) # add noise to range observation z = np.zeros((3, 0)) for i in range(len(rfid[:, 0])): dx = rfid[i, 0] - xTrue[0, 0] dy = rfid[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_with_noize = angle + np.random.randn() * Q_sim[ 1, 1] ** 0.5 # add noise zi = np.array([dn, pi_2_pi(angle_with_noize), i]).reshape(3, 1) z = np.hstack((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 + OFFSET_YAW_RATE_NOISE ud = np.array([ud1, ud2]).reshape(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L277-L304
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27 ]
92.857143
[]
0
false
96.330275
28
3
100
0
def observation(xTrue, xd, u, rfid): # calc true state xTrue = motion_model(xTrue, u) # add noise to range observation z = np.zeros((3, 0)) for i in range(len(rfid[:, 0])): dx = rfid[i, 0] - xTrue[0, 0] dy = rfid[i, 1] - xTrue[1, 0] d = math.hypot(dx, dy) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RANGE: dn = d + np.random.randn() * Q_sim[0, 0] ** 0.5 # add noise angle_with_noize = angle + np.random.randn() * Q_sim[ 1, 1] ** 0.5 # add noise zi = np.array([dn, pi_2_pi(angle_with_noize), i]).reshape(3, 1) z = np.hstack((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 + OFFSET_YAW_RATE_NOISE ud = np.array([ud1, ud2]).reshape(2, 1) xd = motion_model(xd, ud) return xTrue, z, xd, ud
1,426
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
motion_model
(x, u)
return x
307
320
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u x[2, 0] = pi_2_pi(x[2, 0]) return x
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L307-L320
2
[ 0, 1, 4, 5, 8, 9, 10, 11, 12, 13 ]
71.428571
[]
0
false
96.330275
14
1
100
0
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = F @ x + B @ u x[2, 0] = pi_2_pi(x[2, 0]) return x
1,427
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
pi_2_pi
(angle)
return (angle + math.pi) % (2 * math.pi) - math.pi
323
324
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L323-L324
2
[ 0, 1 ]
100
[]
0
true
96.330275
2
1
100
0
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
1,428
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
main
()
327
391
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [15.0, 15.0], [10.0, 20.0], [3.0, 15.0], [-5.0, 20.0], [-5.0, 5.0], [-10.0, 15.0] ]) n_landmark = RFID.shape[0] # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) # SLAM estimation xTrue = np.zeros((STATE_SIZE, 1)) # True state xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue particles = [Particle(n_landmark) for _ in range(N_PARTICLE)] while SIM_TIME >= time: time += DT u = calc_input(time) xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) particles = fast_slam1(particles, ud, z) xEst = calc_final_state(particles) x_state = xEst[0: STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") for i in range(N_PARTICLE): plt.plot(particles[i].x, particles[i].y, ".r") plt.plot(particles[i].lm[:, 0], particles[i].lm[:, 1], "xb") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.plot(xEst[0], xEst[1], "xk") plt.axis("equal") plt.grid(True) plt.pause(0.001)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L327-L391
2
[ 0, 1, 2, 3, 4, 5, 6, 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 ]
74.509804
[]
0
false
96.330275
65
5
100
0
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [15.0, 15.0], [10.0, 20.0], [3.0, 15.0], [-5.0, 20.0], [-5.0, 5.0], [-10.0, 15.0] ]) n_landmark = RFID.shape[0] # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) # SLAM estimation xTrue = np.zeros((STATE_SIZE, 1)) # True state xDR = np.zeros((STATE_SIZE, 1)) # Dead reckoning # history hxEst = xEst hxTrue = xTrue hxDR = xTrue particles = [Particle(n_landmark) for _ in range(N_PARTICLE)] while SIM_TIME >= time: time += DT u = calc_input(time) xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID) particles = fast_slam1(particles, ud, z) xEst = calc_final_state(particles) x_state = xEst[0: STATE_SIZE] # store data history hxEst = np.hstack((hxEst, x_state)) hxDR = np.hstack((hxDR, xDR)) hxTrue = np.hstack((hxTrue, xTrue)) if show_animation: # pragma: no cover plt.cla() # for stopping simulation with the esc key. plt.gcf().canvas.mpl_connect( 'key_release_event', lambda event: [exit(0) if event.key == 'escape' else None]) plt.plot(RFID[:, 0], RFID[:, 1], "*k") for i in range(N_PARTICLE): plt.plot(particles[i].x, particles[i].y, ".r") plt.plot(particles[i].lm[:, 0], particles[i].lm[:, 1], "xb") plt.plot(hxTrue[0, :], hxTrue[1, :], "-b") plt.plot(hxDR[0, :], hxDR[1, :], "-k") plt.plot(hxEst[0, :], hxEst[1, :], "-r") plt.plot(xEst[0], xEst[1], "xk") plt.axis("equal") plt.grid(True) plt.pause(0.001)
1,429
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
SLAM/FastSLAM1/fast_slam1.py
Particle.__init__
(self, n_landmark)
37
45
def __init__(self, n_landmark): self.w = 1.0 / N_PARTICLE self.x = 0.0 self.y = 0.0 self.yaw = 0.0 # landmark x-y positions self.lm = np.zeros((n_landmark, LM_SIZE)) # landmark position covariance self.lmP = np.zeros((n_landmark * LM_SIZE, LM_SIZE))
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/SLAM/FastSLAM1/fast_slam1.py#L37-L45
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
96.330275
9
1
100
0
def __init__(self, n_landmark): self.w = 1.0 / N_PARTICLE self.x = 0.0 self.y = 0.0 self.yaw = 0.0 # landmark x-y positions self.lm = np.zeros((n_landmark, LM_SIZE)) # landmark position covariance self.lmP = np.zeros((n_landmark * LM_SIZE, LM_SIZE))
1,430
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
main
()
Creates an arm using the NLinkArm class and uses its inverse kinematics to move it to the desired position.
Creates an arm using the NLinkArm class and uses its inverse kinematics to move it to the desired position.
28
64
def main(): # pragma: no cover """ Creates an arm using the NLinkArm class and uses its inverse kinematics to move it to the desired position. """ link_lengths = [1] * N_LINKS joint_angles = np.array([0] * N_LINKS) goal_pos = [N_LINKS, 0] arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation) state = WAIT_FOR_NEW_GOAL solution_found = False while True: old_goal = np.array(goal_pos) goal_pos = np.array(arm.goal) end_effector = arm.end_effector errors, distance = distance_to_goal(end_effector, goal_pos) # State machine to allow changing of goal before current goal has been reached if state is WAIT_FOR_NEW_GOAL: if distance > 0.1 and not solution_found: joint_goal_angles, solution_found = inverse_kinematics( link_lengths, joint_angles, goal_pos) if not solution_found: print("Solution could not be found.") state = WAIT_FOR_NEW_GOAL arm.goal = end_effector elif solution_found: state = MOVING_TO_GOAL elif state is MOVING_TO_GOAL: if distance > 0.1 and all(old_goal == goal_pos): joint_angles = joint_angles + Kp * \ ang_diff(joint_goal_angles, joint_angles) * dt else: state = WAIT_FOR_NEW_GOAL solution_found = False arm.update_joints(joint_angles)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L28-L64
2
[]
0
[]
0
false
93.82716
37
10
100
2
def main(): # pragma: no cover link_lengths = [1] * N_LINKS joint_angles = np.array([0] * N_LINKS) goal_pos = [N_LINKS, 0] arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation) state = WAIT_FOR_NEW_GOAL solution_found = False while True: old_goal = np.array(goal_pos) goal_pos = np.array(arm.goal) end_effector = arm.end_effector errors, distance = distance_to_goal(end_effector, goal_pos) # State machine to allow changing of goal before current goal has been reached if state is WAIT_FOR_NEW_GOAL: if distance > 0.1 and not solution_found: joint_goal_angles, solution_found = inverse_kinematics( link_lengths, joint_angles, goal_pos) if not solution_found: print("Solution could not be found.") state = WAIT_FOR_NEW_GOAL arm.goal = end_effector elif solution_found: state = MOVING_TO_GOAL elif state is MOVING_TO_GOAL: if distance > 0.1 and all(old_goal == goal_pos): joint_angles = joint_angles + Kp * \ ang_diff(joint_goal_angles, joint_angles) * dt else: state = WAIT_FOR_NEW_GOAL solution_found = False arm.update_joints(joint_angles)
1,453
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
inverse_kinematics
(link_lengths, joint_angles, goal_pos)
return joint_angles, False
Calculates the inverse kinematics using the Jacobian inverse method.
Calculates the inverse kinematics using the Jacobian inverse method.
67
79
def inverse_kinematics(link_lengths, joint_angles, goal_pos): """ Calculates the inverse kinematics using the Jacobian inverse method. """ for iteration in range(N_ITERATIONS): current_pos = forward_kinematics(link_lengths, joint_angles) errors, distance = distance_to_goal(current_pos, goal_pos) if distance < 0.1: print("Solution found in %d iterations." % iteration) return joint_angles, True J = jacobian_inverse(link_lengths, joint_angles) joint_angles = joint_angles + np.matmul(J, errors) return joint_angles, False
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L67-L79
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
92.307692
[ 12 ]
7.692308
false
93.82716
13
3
92.307692
1
def inverse_kinematics(link_lengths, joint_angles, goal_pos): for iteration in range(N_ITERATIONS): current_pos = forward_kinematics(link_lengths, joint_angles) errors, distance = distance_to_goal(current_pos, goal_pos) if distance < 0.1: print("Solution found in %d iterations." % iteration) return joint_angles, True J = jacobian_inverse(link_lengths, joint_angles) joint_angles = joint_angles + np.matmul(J, errors) return joint_angles, False
1,454
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
get_random_goal
()
return [SAREA * random() - SAREA / 2.0, SAREA * random() - SAREA / 2.0]
82
86
def get_random_goal(): from random import random SAREA = 15.0 return [SAREA * random() - SAREA / 2.0, SAREA * random() - SAREA / 2.0]
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L82-L86
2
[ 0, 1, 2, 3 ]
80
[]
0
false
93.82716
5
1
100
0
def get_random_goal(): from random import random SAREA = 15.0 return [SAREA * random() - SAREA / 2.0, SAREA * random() - SAREA / 2.0]
1,455
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
animation
()
89
129
def animation(): link_lengths = [1] * N_LINKS joint_angles = np.array([0] * N_LINKS) goal_pos = get_random_goal() arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation) state = WAIT_FOR_NEW_GOAL solution_found = False i_goal = 0 while True: old_goal = np.array(goal_pos) goal_pos = np.array(arm.goal) end_effector = arm.end_effector errors, distance = distance_to_goal(end_effector, goal_pos) # State machine to allow changing of goal before current goal has been reached if state is WAIT_FOR_NEW_GOAL: if distance > 0.1 and not solution_found: joint_goal_angles, solution_found = inverse_kinematics( link_lengths, joint_angles, goal_pos) if not solution_found: print("Solution could not be found.") state = WAIT_FOR_NEW_GOAL arm.goal = get_random_goal() elif solution_found: state = MOVING_TO_GOAL elif state is MOVING_TO_GOAL: if distance > 0.1 and all(old_goal == goal_pos): joint_angles = joint_angles + Kp * \ ang_diff(joint_goal_angles, joint_angles) * dt else: state = WAIT_FOR_NEW_GOAL solution_found = False arm.goal = get_random_goal() i_goal += 1 if i_goal >= 5: break arm.update_joints(joint_angles)
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L89-L129
2
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 25, 26, 27, 28, 29, 32, 33, 34, 35, 36, 37, 38, 39, 40 ]
85.365854
[ 22, 23, 24 ]
7.317073
false
93.82716
41
11
92.682927
0
def animation(): link_lengths = [1] * N_LINKS joint_angles = np.array([0] * N_LINKS) goal_pos = get_random_goal() arm = NLinkArm(link_lengths, joint_angles, goal_pos, show_animation) state = WAIT_FOR_NEW_GOAL solution_found = False i_goal = 0 while True: old_goal = np.array(goal_pos) goal_pos = np.array(arm.goal) end_effector = arm.end_effector errors, distance = distance_to_goal(end_effector, goal_pos) # State machine to allow changing of goal before current goal has been reached if state is WAIT_FOR_NEW_GOAL: if distance > 0.1 and not solution_found: joint_goal_angles, solution_found = inverse_kinematics( link_lengths, joint_angles, goal_pos) if not solution_found: print("Solution could not be found.") state = WAIT_FOR_NEW_GOAL arm.goal = get_random_goal() elif solution_found: state = MOVING_TO_GOAL elif state is MOVING_TO_GOAL: if distance > 0.1 and all(old_goal == goal_pos): joint_angles = joint_angles + Kp * \ ang_diff(joint_goal_angles, joint_angles) * dt else: state = WAIT_FOR_NEW_GOAL solution_found = False arm.goal = get_random_goal() i_goal += 1 if i_goal >= 5: break arm.update_joints(joint_angles)
1,456
AtsushiSakai/PythonRobotics
15ab19688b2f6c03ee91a853f1f8cc9def84d162
ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py
forward_kinematics
(link_lengths, joint_angles)
return np.array([x, y]).T
132
137
def forward_kinematics(link_lengths, joint_angles): x = y = 0 for i in range(1, N_LINKS + 1): x += link_lengths[i - 1] * np.cos(np.sum(joint_angles[:i])) y += link_lengths[i - 1] * np.sin(np.sum(joint_angles[:i])) return np.array([x, y]).T
https://github.com/AtsushiSakai/PythonRobotics/blob/15ab19688b2f6c03ee91a853f1f8cc9def84d162/project2/ArmNavigation/n_joint_arm_to_point_control/n_joint_arm_to_point_control.py#L132-L137
2
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.82716
6
2
100
0
def forward_kinematics(link_lengths, joint_angles): x = y = 0 for i in range(1, N_LINKS + 1): x += link_lengths[i - 1] * np.cos(np.sum(joint_angles[:i])) y += link_lengths[i - 1] * np.sin(np.sum(joint_angles[:i])) return np.array([x, y]).T
1,457