@iStarLee
2019-08-29T16:02:46.000000Z
字数 7643
阅读 711
SLAM
In this simulation, the robot has a state vector includes 4 states at time .
x, y are a 2D x-y position, is orientation, and v is velocity. In the code, "xEst" means the state vector. And, is covariace matrix of the state, is covariance matrix of process noise, is covariance matrix of observation noise at time . The robot has a speed sensor and a gyro sensor. So, the input vecor can be used as each time step
The robot model is
is a time interval.
Its Jacobian matrix is
The robot can get x-y position infomation from GPS. So GPS Observation model is
Localization process using Extendted Kalman Filter is
The robot is running at linear speed 1.0 m/s, twist speed is 0.1 rad/s. There are four already known landmark, which are located at (10,-2),(15,10),(3,15),(-5,20). The motion model noise and observation noise are gaussian noise, the mean is 0, the covariance is [0,1].
In our EKF simulation system, we show the three kind of line results.

"""Extended Kalman Filter SLAM exampleauthor: Atsushi Sakai (@Atsushi_twi)"""import mathimport numpy as npimport matplotlib.pyplot as plt# EKF state covarianceCx = np.diag([0.5, 0.5, np.deg2rad(30.0)])**2# Simulation parameterQsim = np.diag([0.2, np.deg2rad(1.0)])**2Rsim = np.diag([1.0, np.deg2rad(10.0)])**2DT = 0.1 # time tick [s]SIM_TIME = 50.0 # simulation time [s]MAX_RANGE = 20.0 # maximum observation rangeM_DIST_TH = 2.0 # Threshold of Mahalanobis distance for data association.STATE_SIZE = 3 # State size [x,y,yaw]LM_SIZE = 2 # LM state size [x,y]show_animation = Truedef ekf_slam(xEst, PEst, u, z):# PredictS = STATE_SIZExEst[0:S] = motion_model(xEst[0:S], u)G, Fx = jacob_motion(xEst[0:S], u)PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * FxinitP = np.eye(2)# Updatefor iz in range(len(z[:, 0])): # for each observationminid = search_correspond_LM_ID(xEst, PEst, z[iz, 0:2])nLM = calc_n_LM(xEst)if minid == nLM:print("New LM")# Extend state and covariance matrixxAug = np.vstack((xEst, calc_LM_Pos(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 = xAugPEst = PAuglm = get_LM_Pos_from_state(xEst, minid)y, S, H = calc_innovation(lm, xEst, PEst, z[iz, 0:2], minid)K = (PEst @ H.T) @ np.linalg.inv(S)xEst = xEst + (K @ y)PEst = (np.eye(len(xEst)) - (K @ H)) @ PEstxEst[2] = pi_2_pi(xEst[2])return xEst, PEstdef calc_input():v = 1.0 # [m/s]yawrate = 0.1 # [rad/s]u = np.array([[v, yawrate]]).Treturn udef observation(xTrue, xd, u, RFID):xTrue = motion_model(xTrue, u)# add noise to gps x-yz = 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.sqrt(dx**2 + dy**2)angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0])if d <= MAX_RANGE:dn = d + np.random.randn() * Qsim[0, 0] # add noiseanglen = angle + np.random.randn() * Qsim[1, 1] # add noisezi = np.array([dn, anglen, i])z = np.vstack((z, zi))# add noise to inputud = np.array([[u[0, 0] + np.random.randn() * Rsim[0, 0],u[1, 0] + np.random.randn() * Rsim[1, 1]]]).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 @ u)return xdef calc_n_LM(x):n = int((len(x) - STATE_SIZE) / LM_SIZE)return ndef 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] * math.sin(x[2, 0])],[0.0, 0.0, DT * u[0] * math.cos(x[2, 0])],[0.0, 0.0, 0.0]])G = np.eye(STATE_SIZE) + Fx.T * jF * Fxreturn G, Fx,def calc_LM_Pos(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])#zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1])#zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1])return zpdef get_LM_Pos_from_state(x, ind):lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :]return lmdef search_correspond_LM_ID(xAug, PAug, zi):"""Landmark association with Mahalanobis distance"""nLM = calc_n_LM(xAug)mdist = []for i in range(nLM):lm = get_LM_Pos_from_state(xAug, i)y, S, H = calc_innovation(lm, xAug, PAug, zi, i)mdist.append(y.T @ np.linalg.inv(S) @ y)mdist.append(M_DIST_TH) # new landmarkminid = mdist.index(min(mdist))return miniddef calc_innovation(lm, xEst, PEst, z, LMid):delta = lm - xEst[0:2]q = (delta.T @ delta)[0, 0]zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0]zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]])y = (z - zp).Ty[1] = pi_2_pi(y[1])H = jacobH(q, delta, xEst, LMid + 1)S = H @ PEst @ H.T + Cx[0:2, 0:2]return y, S, Hdef jacobH(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], - 1.0, - delta[1, 0], delta[0, 0]]])G = G / qnLM = 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 @ Freturn Hdef pi_2_pi(angle):return (angle + math.pi) % (2 * math.pi) - math.pidef 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# historyhxEst = xEsthxTrue = xTruehxDR = xTruewhile SIM_TIME >= time:time += DTu = 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 historyhxEst = np.hstack((hxEst, x_state))hxDR = np.hstack((hxDR, xDR))hxTrue = np.hstack((hxTrue, xTrue))if show_animation: # pragma: no coverplt.cla()plt.plot(RFID[:, 0], RFID[:, 1], "*b", lw='3')plt.plot(xEst[0], xEst[1], ".r")# plot landmarkfor i in range(calc_n_LM(xEst)):plt.plot(xEst[STATE_SIZE + i * 2],xEst[STATE_SIZE + i * 2 + 1], "xg")gt,=plt.plot(hxTrue[0, :],hxTrue[1, :], "-g")dr,=plt.plot(hxDR[0, :],hxDR[1, :], "-k")est,=plt.plot(hxEst[0, :],hxEst[1, :], "-r")plt.axis("equal")plt.xlabel('x/m')plt.ylabel('y/m')plt.grid(True)plt.legend([gt,dr,est],['Ground True','Dead Reckoning', 'EKF SLAM Estimation'],loc='best')plt.pause(0.001)if __name__ == '__main__':main()