"""Graph based SLAM exampleauthor: Atsushi Sakai (@Atsushi_twi)Ref[A Tutorial on Graph-Based SLAM](http://www2.informatik.uni-freiburg.de/~stachnis/pdf/grisetti10titsmag.pdf)"""import copyimport itertoolsimport mathimport matplotlib.pyplot as pltimport numpy as npfrom scipy.spatial.transform import Rotation as Rot# Simulation parameterQ_sim = np.diag([0.2, np.deg2rad(1.0)]) ** 2R_sim = np.diag([0.1, np.deg2rad(10.0)]) ** 2DT = 2.0 # time tick [s]SIM_TIME = 100.0 # simulation time [s]MAX_RANGE = 30.0 # maximum observation rangeSTATE_SIZE = 3 # State size [x,y,yaw]# Covariance parameter of Graph Based SLAMC_SIGMA1 = 0.1C_SIGMA2 = 0.1C_SIGMA3 = np.deg2rad(1.0)MAX_ITR = 20 # Maximum iterationshow_graph_d_time = 20.0 # [s]show_animation = Trueclass Edge:def __init__(self):self.e = np.zeros((3, 1))self.omega = np.zeros((3, 3)) # information matrixself.d1 = 0.0self.d2 = 0.0self.yaw1 = 0.0self.yaw2 = 0.0self.angle1 = 0.0self.angle2 = 0.0self.id1 = 0self.id2 = 0def cal_observation_sigma():sigma = np.zeros((3, 3))sigma[0, 0] = C_SIGMA1 ** 2sigma[1, 1] = C_SIGMA2 ** 2sigma[2, 2] = C_SIGMA3 ** 2return sigmadef calc_rotational_matrix(angle):return Rot.from_euler('z', angle).as_matrix()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 + tmp2edge.e[1, 0] = y2 - y1 - tmp3 + tmp4edge.e[2, 0] = 0Rt1 = calc_rotational_matrix(tangle1)Rt2 = calc_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, d2edge.yaw1, edge.yaw2 = yaw1, yaw2edge.angle1, edge.angle2 = angle1, angle2edge.id1, edge.id2 = t1, t2return edgedef calc_edges(x_list, z_list):edges = []cost = 0.0z_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 observationfor 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 edgesdef calc_jacobian(edge):t1 = edge.yaw1 + edge.angle1A = 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.angle2B = np.array([[1.0, 0, -edge.d2 * math.sin(t2)],[0, 1.0, edge.d2 * math.cos(t2)],[0, 0, 0]])return A, Bdef fill_H_and_b(H, b, edge):A, B = calc_jacobian(edge)id1 = edge.id1 * STATE_SIZEid2 = edge.id2 * STATE_SIZEH[id1:id1 + STATE_SIZE, id1:id1 + STATE_SIZE] += A.T @ edge.omega @ AH[id1:id1 + STATE_SIZE, id2:id2 + STATE_SIZE] += A.T @ edge.omega @ BH[id2:id2 + STATE_SIZE, id1:id1 + STATE_SIZE] += B.T @ edge.omega @ AH[id2:id2 + STATE_SIZE, id2:id2 + STATE_SIZE] += B.T @ edge.omega @ Bb[id1:id1 + STATE_SIZE] += (A.T @ edge.omega @ edge.e)b[id2:id2 + STATE_SIZE] += (B.T @ edge.omega @ edge.e)return H, bdef 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_SIZEfor 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 originH[0:STATE_SIZE, 0:STATE_SIZE] += np.identity(STATE_SIZE)dx = - np.linalg.inv(H) @ bfor i in range(nt):x_opt[0:3, i] += dx[i * 3:i * 3 + 3, 0]diff = dx.T @ dxprint("iteration: %d, diff: %f" % (itr + 1, diff))if diff < 1.0e-5:breakreturn x_optdef calc_input():v = 1.0 # [m/s]yaw_rate = 0.1 # [rad/s]u = np.array([[v, yaw_rate]]).Treturn udef observation(xTrue, xd, u, RFID):xTrue = motion_model(xTrue, u)# add noise to gps x-yz = 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 noiseangle_noise = np.random.randn() * Q_sim[1, 1]angle += angle_noisephi += angle_noisezi = np.array([dn, angle, phi, i])z = np.vstack((z, zi))# add noise to inputud1 = 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]]).Txd = motion_model(xd, ud)return xTrue, z, xd, uddef 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 @ ureturn xdef pi_2_pi(angle):return (angle + math.pi) % (2 * math.pi) - math.pidef 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# historyhxTrue = []hxDR = []hz = []d_time = 0.0init = Falsewhile SIM_TIME >= time:if not init:hxTrue = xTruehxDR = xTrueinit = Trueelse:hxDR = np.hstack((hxDR, xDR))hxTrue = np.hstack((hxTrue, xTrue))time += DTd_time += DTu = 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.0if show_animation: # pragma: no coverplt.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)if __name__ == '__main__':main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。