Python实现目标轨迹跟踪(LQR算法)(可用于移植至C语言MCU触屏识别,自动驾驶轨迹与目标跟踪算法)

        Python实现目标轨迹跟踪(LQR算法)(可用于移植至C语言MCU触屏识别,自动驾驶轨迹与目标跟踪算法)-------文章摘自https://blog.youkuaiyun.com/nn243823163/article/details/124456694

        感谢原作者,稍作修改,并添加三次插值函数后引用,谢谢原作者提供整个算法的实现,之前在相关触摸屏行业有相关经验,发现该函数可用于轨迹平滑,轨迹跟踪,目标轨迹跟随,应用很好,所以写这篇文章来补充笔者与读者的相应知识。实现代码如下:

# 导入相关包
 
import math
 
import sys
 
import os
 
import matplotlib.pyplot as plt
 
import numpy as np

import bisect

from scipy import interpolate

#import scipy.linalg as la
from scipy import linalg as lg #导入scipy库的linalg模块 
 
# cubic_spline_planner为自己实现的三次样条插值方法
 
#try:
 
#    from cubic_spline_planner import *
 
#except ImportError:
 
#    raise

class Spline:
    """
    Cubic Spline class
    """

    def __init__(self, x, y):
        self.b, self.c, self.d, self.w = [], [], [], []

        self.x = x
        self.y = y

        self.nx = len(x)  # dimension of x
        h = np.diff(x)

        # calc coefficient a
        self.a = [iy for iy in y]

        # calc coefficient c
        A = self.__calc_A(h)
        B = self.__calc_B(h)
        self.c = np.linalg.solve(A, B)
        #  print(self.c1)

        # calc spline coefficient b and d
        for i in range(self.nx - 1):
            self.d.append((self.c[i + 1] - self.c[i]) / (3.0 * h[i]))
            tb = (self.a[i + 1] - self.a[i]) / h[i] - h[i] * \
                (self.c[i + 1] + 2.0 * self.c[i]) / 3.0
            self.b.append(tb)

    def calc(self, t):
        """
        Calc position

        if t is outside of the input x, return None

        """

        if t < self.x[0]:
            return None
        elif t > self.x[-1]:
            return None

        i = self.__search_index(t)
        dx = t - self.x[i]
        result = self.a[i] + self.b[i] * dx + \
            self.c[i] * dx ** 2.0 + self.d[i] * dx ** 3.0

        return result

    def calcd(self, t):
        """
        Calc first derivative

        if t is outside of the input x, return None
        """

        if t < self.x[0]:
            return None
        elif t > self.x[-1]:
            return None

        i = self.__search_index(t)
        dx = t - self.x[i]
        result = self.b[i] + 2.0 * self.c[i] * dx + 3.0 * self.d[i] * dx ** 2.0
        return result

    def calcdd(self, t):
        """
        Calc second derivative
        """

        if t < self.x[0]:
            return None
        elif t > self.x[-1]:
            return None

        i = self.__search_index(t)
        dx = t - self.x[i]
        result = 2.0 * self.c[i] + 6.0 * self.d[i] * dx
        return result

    def __search_index(self, x):
        """
        search data segment index
        """
        return bisect.bisect(self.x, x) - 1

    def __calc_A(self, h):
        """
        calc matrix A for spline coefficient c
        """
        A = np.zeros((self.nx, self.nx))
        A[0, 0] = 1.0
        for i in range(self.nx - 1):
            if i != (self.nx - 2):
                A[i + 1, i + 1] = 2.0 * (h[i] + h[i + 1])
            A[i + 1, i] = h[i]
            A[i, i + 1] = h[i]

        A[0, 1] = 0.0
        A[self.nx - 1, self.nx - 2] = 0.0
        A[self.nx - 1, self.nx - 1] = 1.0
        #  print(A)
        return A

    def __calc_B(self, h):
        """
        calc matrix B for spline coefficient c
        """
        B = np.zeros(self.nx)
        for i in range(self.nx - 2):
            B[i + 1] = 3.0 * (self.a[i + 2] - self.a[i + 1]) / \
                h[i + 1] - 3.0 * (self.a[i + 1] - self.a[i]) / h[i]
        return B


class Spline2D:
    """
    2D Cubic Spline class

    """

    def __init__(self, x, y):
        self.s = self.__calc_s(x, y)
        self.sx = Spline(self.s, x)
        self.sy = Spline(self.s, y)

    def __calc_s(self, x, y):
        dx = np.diff(x)
        dy = np.diff(y)
        self.ds = np.hypot(dx, dy)
        s = [0]
        s.extend(np.cumsum(self.ds))
        return s

    def calc_position(self, s):
        """
        calc position
        """
        x = self.sx.calc(s)
        y = self.sy.calc(s)

        return x, y

    def calc_curvature(self, s):
        """
        calc curvature
        """
        dx = self.sx.calcd(s)
        ddx = self.sx.calcdd(s)
        dy = self.sy.calcd(s)
        ddy = self.sy.calcdd(s)
        k = (ddy * dx - ddx * dy) / ((dx ** 2 + dy ** 2)**(3 / 2))
        return k

    def calc_yaw(self, s):
        """
        calc yaw
        """
        dx = self.sx.calcd(s)
        dy = self.sy.calcd(s)
        yaw = math.atan2(dy, dx)
        return yaw


def calc_spline_course(x, y, ds=0.1):
    sp = Spline2D(x, y)
    s = list(np.arange(0, sp.s[-1], ds))

    rx, ry, ryaw, rk = [], [], [], []
    for i_s in s:
        ix, iy = sp.calc_position(i_s)
        rx.append(ix)
        ry.append(iy)
        ryaw.append(sp.calc_yaw(i_s))
        rk.append(sp.calc_curvature(i_s))

    return rx, ry, ryaw, rk, s

# 设置轨迹会经过的点
 
ax = [0.0, 6.0, 12.5, 10.0, 17.5, 20.0, 25.0,37.5,50.0,62.5,80.0]
 
ay = [0.0, -3.0, -5.0, 6.5, 3.0, 0.0, 0.0,7.8,-6.9,4.1,-1.3]
 
goal = [ax[-1], ay[-1]]
 
 
 
# 使用三次样条插值方法,根据途经点生成轨迹,x、y、yaw、曲率k,距离s
 
cx, cy, cyaw, ck, s = calc_spline_course(
 
        ax, ay, ds=0.1)
 
# 3. 绘制平滑曲线

# 插值法,50表示插值个数,个数>=实际数据个数,一般来说差值个数越多,曲线越平滑
#x_new = np.linspace(0,max(ax),50) 
 
#y_smooth = interpolate.interp1d(ax, ay, kind='cubic')

#yy = y_smooth(x_new)

#plt.plot(x_new, y_smooth)
 
# 绘制规划好的轨迹
 
plt.plot(ax, ay, "xb", label="waypoints")
 
plt.plot(cx, cy, "-r", label="target course")

#plt.plot(x_new, yy, "-r", label="target course")

plt.show() 

# 设置目标速度

target_speed = 10.0 / 3.6  # simulation parameter km/h -> m/s
 
 
 
speed_profile = [target_speed] * len(cyaw)
 
 
 
direction = 1.0
 
 
 
# 转弯幅度较大时将速度设置为0,并将速度方向翻转
 
# Set stop point
 
for i in range(len(cyaw) - 1):
 
    dyaw = abs(cyaw[i + 1] - cyaw[i])
 
    switch = math.pi / 4.0 <= dyaw < math.pi / 2.0
 
 
 
    if switch:
 
        direction *= -1
 
 
 
    if direction != 1.0:
 
        speed_profile[i] = - target_speed
 
    else:
 
        speed_profile[i] = target_speed
 
 
 
    if switch:
 
        speed_profile[i] = 0.0
 
 
 
# 靠近目的地时,速度降低       
 
# speed down
 
for i in range(40):
 
    speed_profile[-i] = target_speed / (50 - i)
 
    if speed_profile[-i] <= 1.0 / 3.6:
 
        speed_profile[-i] = 1.0 / 3.6
 
 
 
plt.plot(speed_profile, "-b", label="speed_profile")



# 定义LQR 计算所需要的数据结构,以及DLQR的求解方法 
 
 
# State 对象表示自车的状态,位置x、y,以及横摆角yaw、速度v
 
class State:
 
 
 
    def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
 
        self.x = x
 
        self.y = y
 
        self.yaw = yaw
 
        self.v = v
 
 
 
# 更新自车的状态,采样时间足够小,则认为这段时间内速度相同,加速度相同,使用匀速模型更新位置
 
def update(state, a, delta):
 
    max_steer = 90

    dt = 0.1

    L = 1
 
    if delta >= max_steer:
 
        delta = max_steer
 
    if delta <= - max_steer:
 
        delta = - max_steer
 
 
 
    state.x = state.x + state.v * math.cos(state.yaw) * dt
 
    state.y = state.y + state.v * math.sin(state.yaw) * dt
 
    state.yaw = state.yaw + state.v / L * math.tan(delta) * dt
 
    state.v = state.v + a * dt
 
 
 
    return state
 
 
 
 
 
def pi_2_pi(angle):
 
    return (angle + math.pi) % (2 * math.pi) - math.pi
 
 
 
 
 
# 实现离散Riccati equation 的求解方法
 
def solve_dare(A, B, Q, R):
 
    """
    solve a discrete time_Algebraic Riccati equation (DARE)
    """
 
    x = Q
 
    x_next = Q
 
    max_iter = 150
 
    eps = 0.01
 
 
 
    for i in range(max_iter):
 
        x_next = A.T @ x @ A - A.T @ x @ B @ lg.inv(R + B.T @ x @ B) @ B.T @ x @ A + Q
 
        if (abs(x_next - x)).max() < eps:
 
            break
 
        x = x_next
 
 
 
    return x_next
 
 
 
# 返回值K 即为LQR 问题求解方法中系数K的解
 
def dlqr(A, B, Q, R):
 
    """Solve the discrete time lqr controller.
    x[k+1] = A x[k] + B u[k]
    cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
    # ref Bertsekas, p.151
    """
 
 
 
    # first, try to solve the ricatti equation
 
    X = solve_dare(A, B, Q, R)
 
 
 
    # compute the LQR gain
 
    K = lg.inv(B.T @ X @ B + R) @ (B.T @ X @ A)
 
 
 
    eig_result = lg.eig(A - B @ K)
 
 
 
    return K, X, eig_result[0]
 
 
 
# 计算距离自车当前位置最近的参考点
 
def calc_nearest_index(state, cx, cy, cyaw):
 
    dx = [state.x - icx for icx in cx]
 
    dy = [state.y - icy for icy in cy]
 
 
 
    d = [idx ** 2 + idy ** 2 for (idx, idy) in zip(dx, dy)]
 
 
 
    mind = min(d)
 
 
 
    ind = d.index(mind)
 
 
 
    mind = math.sqrt(mind)
 
 
 
    dxl = cx[ind] - state.x
 
    dyl = cy[ind] - state.y
 
 
 
    angle = pi_2_pi(cyaw[ind] - math.atan2(dyl, dxl))
 
    if angle < 0:
 
        mind *= -1
 
 
 
    return ind, mind


# 设置起点的参数
 
T = 500.0  # max simulation time
 
goal_dis = 0.3
 
stop_speed = 0.05
 
 
 
state = State(x=-0.0, y=-0.0, yaw=0.0, v=0.0)
 
 
 
time = 0.0
 
x = [state.x]
 
y = [state.y]
 
yaw = [state.yaw]
 
v = [state.v]
 
t = [0.0]
 
 
 
pe, pth_e = 0.0, 0.0




# 配置LQR 的参数
 
# === Parameters =====
 
 
 
# LQR parameter
 
lqr_Q = np.eye(5)
 
lqr_R = np.eye(2)
 
dt = 0.1  # time tick[s],采样时间
 
L = 0.5  # Wheel base of the vehicle [m],车辆轴距
 
max_steer = np.deg2rad(45.0)  # maximum steering angle[rad]
 
 
 
show_animation = True
 
 
 
while T >= time:
 
    #ind, e = calc_nearest_index(state, cx, cy, cyaw)

    ind, e = calc_nearest_index(state, cx, cy, cyaw)
 
 
    sp = speed_profile
 
    tv = sp[ind]
 
 
 
    k = ck[ind]
 
    v_state = state.v
 
    th_e = pi_2_pi(state.yaw - cyaw[ind])
 
 
 
    # 构建LQR表达式,X(k+1) = A * X(k) + B * u(k), 使用Riccati equation 求解LQR问题
 
#    dt表示采样周期,v表示当前自车的速度
 
#    A = [1.0, dt, 0.0, 0.0, 0.0
 
#          0.0, 0.0, v, 0.0, 0.0]
 
#          0.0, 0.0, 1.0, dt, 0.0]
 
#          0.0, 0.0, 0.0, 0.0, 0.0]
 
#          0.0, 0.0, 0.0, 0.0, 1.0]
 
    A = np.zeros((5, 5))
 
    A[0, 0] = 1.0
 
    A[0, 1] = dt
 
    A[1, 2] = v_state
 
    A[2, 2] = 1.0
 
    A[2, 3] = dt
 
    A[4, 4] = 1.0
 
 
 
    # 构建B矩阵,L是自车的轴距
 
    # B = [0.0, 0.0
 
    #    0.0, 0.0
 
    #    0.0, 0.0
 
    #    v/L, 0.0
 
    #    0.0, dt]
 
    B = np.zeros((5, 2))
 
    B[3, 0] = v_state / L
 
    B[4, 1] = dt
 
 
 
    K, _, _ = dlqr(A, B, lqr_Q, lqr_R)
 
 
 
    # state vector,构建状态矩阵
 
    # x = [e, dot_e, th_e, dot_th_e, delta_v]
 
    # e: lateral distance to the path, e是自车到轨迹的距离
 
    # dot_e: derivative of e, dot_e是自车到轨迹的距离的变化率
 
    # th_e: angle difference to the path, th_e是自车与期望轨迹的角度偏差
 
    # dot_th_e: derivative of th_e, dot_th_e是自车与期望轨迹的角度偏差的变化率
 
    # delta_v: difference between current speed and target speed,delta_v是当前车速与期望车速的偏差
 
    X = np.zeros((5, 1))
 
    X[0, 0] = e
 
    X[1, 0] = (e - pe) / dt
 
    X[2, 0] = th_e
 
    X[3, 0] = (th_e - pth_e) / dt
 
    X[4, 0] = v_state - tv
 
 
 
    # input vector,构建输入矩阵u
 
    # u = [delta, accel]
 
    # delta: steering angle,前轮转角
 
    # accel: acceleration,自车加速度
 
    ustar = -K @ X
 
 
 
    # calc steering input
 
    ff = math.atan2(L * k, 1)  # feedforward steering angle
 
    fb = pi_2_pi(ustar[0, 0])  # feedback steering angle
 
    delta = ff + fb
 
 
 
    # calc accel input
 
    accel = ustar[1, 0]
 
 
 
    dl, target_ind, pe, pth_e, ai = delta, ind, e, th_e, accel
 
 
 
    state = update(state, ai, dl)
 
 
 
    if abs(state.v) <= stop_speed:
 
        target_ind += 1
 
 
 
    time = time + dt
 
 
 
    # check goal
 
    dx = state.x - goal[0]
 
    dy = state.y - goal[1]
 
    if math.hypot(dx, dy) <= goal_dis:
 
        print("Goal")
 
        break
 
 
 
    x.append(state.x)
 
    y.append(state.y)
 
    yaw.append(state.yaw)
 
    v.append(state.v)
 
    t.append(time)
 
 
 
    if target_ind % 100 == 0 and show_animation:
 
        plt.cla()
 
        # for stopping simulation with the esc key.
 
        plt.gcf().canvas.mpl_connect('key_release_event',
 
                lambda event: [exit(0) if event.key == 'escape' else None])
 
        plt.plot(cx, cy, "-r", label="course")
 
        plt.plot(x, y, "ob", label="trajectory")
 
        plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
 
        plt.axis("equal")
 
        plt.grid(True)
 
        plt.title("speed[km/h]:" + str(round(state.v * 3.6, 2))
 
                  + ",target index:" + str(target_ind) + ", time si: " + str(time))
 
        plt.pause(0.1)

if show_animation:  # pragma: no cover
 
        plt.close()
 
        plt.subplots(1)
 
        plt.plot(ax, ay, "xb", label="waypoints")
 
        plt.plot(cx, cy, "-r", label="target course")
 
        plt.plot(x, y, "-g", label="tracking")
 
        plt.grid(True)
 
        plt.axis("equal")
 
        plt.xlabel("x[m]")
 
        plt.ylabel("y[m]")
 
        plt.legend()
 
 
 
        plt.subplots(1)
 
        plt.plot(s, [np.rad2deg(iyaw) for iyaw in cyaw], "-r", label="yaw")
 
        plt.grid(True)
 
        plt.legend()
 
        plt.xlabel("line length[m]")
 
        plt.ylabel("yaw angle[deg]")
 
 
 
        plt.subplots(1)
 
        plt.plot(s, ck, "-r", label="curvature")
 
        plt.grid(True)
 
        plt.legend()
 
        plt.xlabel("line length[m]")
 
        plt.ylabel("curvature [1/m]")
 
 
 
        plt.show()       

实现效果如下:

原轨迹并插值平滑图(主要应用之一):

曲率图:

 

轨迹跟踪图:

如有疑问,请您留言。如有侵权,请私信告知。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值