程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(2)

手把手教用matlab做无人驾驶(十)--纯跟踪算法(pure control)的补充l---python与matlab/simulink两种语言的编程实现

发布于2019-08-06 10:25     阅读(4286)     评论(0)     点赞(4)     收藏(1)


已经半年没有关注博客了,由于当时工作太忙的原因,现在终于有时间再次回归博客了,再这半年的时间里由于没在,许多人留言希望上传pure control代码,现在这里会上传python与matlab/simulink两个版本代码,仅供参考。欢迎大家以后多多交流,一起写点东西。

好的,言归正传,来说说pure control,部分内容请参考手把手教用matlab做无人驾驶(四),这里再补充点公式:

前轮转角 δ,为了更好的理解纯追踪控制器的原理,我们定义一个新的量:el—— 车辆当前姿态和目标路点在横向上的误差,由此可得夹角正弦:

由上面的正弦定理可得下面:

R=2*sin(a)/Ld

\delta =tan^(-1)(RLd)

由上面的公式可得

alpha = math.atan2(ty - state.rear_y, tx - state.rear_x) - state.yaw

基于上面的公式,我们现在给出python 代码:

 

"""

Path tracking simulation with pure pursuit steering control and PID speed control.

author: Atsushi Sakai (@Atsushi_twi)

"""
import numpy as np
import math
import matplotlib.pyplot as plt


k = 0.1  # look forward gain
Lfc = 2.0  # look-ahead distance
Kp = 1.0  # speed proportional gain
dt = 0.1  # [s]
L = 2.9  # [m] wheel base of vehicle


old_nearest_point_index = None
show_animation = True


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
        self.rear_x = self.x - ((L / 2) * math.cos(self.yaw))
        self.rear_y = self.y - ((L / 2) * math.sin(self.yaw))


def update(state, a, delta):

    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
    state.rear_x = state.x - ((L / 2) * math.cos(state.yaw))
    state.rear_y = state.y - ((L / 2) * math.sin(state.yaw))

    return state


def PIDControl(target, current):
    a = Kp * (target - current)

    return a


def pure_pursuit_control(state, cx, cy, pind):

    ind = calc_target_index(state, cx, cy)

    if pind >= ind:
        ind = pind

    if ind < len(cx):
        tx = cx[ind]
        ty = cy[ind]
    else:
        tx = cx[-1]
        ty = cy[-1]
        ind = len(cx) - 1

    alpha = math.atan2(ty - state.rear_y, tx - state.rear_x) - state.yaw

    Lf = k * state.v + Lfc

    delta = math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0)

    return delta, ind

def calc_distance(state, point_x, point_y):

    dx = state.rear_x - point_x
    dy = state.rear_y - point_y
    return math.sqrt(dx ** 2 + dy ** 2)


def calc_target_index(state, cx, cy):

    global old_nearest_point_index

    if old_nearest_point_index is None:
        # search nearest point index
        dx = [state.rear_x - icx for icx in cx]
        dy = [state.rear_y - icy for icy in cy]
        d = [abs(math.sqrt(idx ** 2 + idy ** 2)) for (idx, idy) in zip(dx, dy)]
        ind = d.index(min(d))
        old_nearest_point_index = ind

    else:
        ind = old_nearest_point_index
        distance_this_index = calc_distance(state, cx[ind], cy[ind])

        while True:
            ind = ind + 1 if (ind + 1) < len(cx) else ind
            print("ind=%d",ind);
            distance_next_index = calc_distance(state, cx[ind], cy[ind])
            if distance_this_index < distance_next_index:
                break
            distance_this_index = distance_next_index
        old_nearest_point_index = ind


    L = 0.0

    #Lf = k * state.v + Lfc
    Lf=Lfc;

    # search look ahead target point index
    while Lf > L and (ind + 1) < len(cx):
        dx = cx[ind] - state.rear_x
        dy = cy[ind] - state.rear_y
        L = math.sqrt(dx ** 2 + dy ** 2)
        ind += 1

    return ind


def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
    """
    Plot arrow
    """

    if not isinstance(x, float):
        for (ix, iy, iyaw) in zip(x, y, yaw):
            plot_arrow(ix, iy, iyaw)
    else:
        plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
                  fc=fc, ec=ec, head_width=width, head_length=width)
        plt.plot(x, y)


def main():
    #  target course
    cx = np.arange(0, 50, 0.1)
    cy = [math.sin(ix / 5.0) * ix / 2.0 for ix in cx]

    target_speed = 10.0 / 3.6  # [m/s]

    T = 100.0  # max simulation time

    # initial state
    state = State(x=-0.0, y=-3.0, yaw=0.0, v=0.0)

    lastIndex = len(cx) - 1
    time = 0.0
    x = [state.x]
    y = [state.y]
    yaw = [state.yaw]
    v = [state.v]
    t = [0.0]
    target_ind = calc_target_index(state, cx, cy)

    while T >= time and lastIndex > target_ind:
        ai = PIDControl(target_speed, state.v)
        di, target_ind = pure_pursuit_control(state, cx, cy, target_ind)
        state = update(state, ai, di)

        time = time + dt

        x.append(state.x)
        y.append(state.y)
        yaw.append(state.yaw)
        v.append(state.v)
        t.append(time)

        if show_animation:  # pragma: no cover
            plt.cla()
            plot_arrow(state.x, state.y, state.yaw)
            plt.plot(cx, cy, "-r", label="course")
            plt.plot(x, y, "-b", label="trajectory")
            plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
            plt.axis("equal")
            plt.grid(True)
            plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4])
            plt.pause(0.001)

    # Test
    assert lastIndex >= target_ind, "Cannot goal"

    if show_animation:  # pragma: no cover
        plt.cla()
        plt.plot(cx, cy, ".r", label="course")
        plt.plot(x, y, "-b", label="trajectory")
        plt.legend()
        plt.xlabel("x[m]")
        plt.ylabel("y[m]")
        plt.axis("equal")
        plt.grid(True)

        plt.subplots(1)
        plt.plot(t, [iv * 3.6 for iv in v], "-r")
        plt.xlabel("Time[s]")
        plt.ylabel("Speed[km/h]")
        plt.grid(True)
        plt.show()


if __name__ == '__main__':
    print("Pure pursuit path tracking simulation start")
    main()

这段代码对于懂python的同学来说很简单,仿真结果如下,这个可以调节参数更好:

 

 

现在给出matlab/simulink 代码:

这里的数据都是基于全局坐标系做的,主要分为三个模块,lookaheadAnalyser、Pure Pursuit、Vehicle Model,其中lookaheadAnalyser主要找到目标点,Pure Pursuit主要是实现控制,Vehicle Model是模型。

仿真结果如下:

lookaheadAnalyser中代码如下,我用了一个fcn函数:

function [y,old_nearest_point_indexnew] = fcn(lookdistance,curpos,repos,old_nearest_point_index)
d=zeros(1,size(repos,1));
curpos = reshape(curpos,1,3)
    %if old_nearest_point_index==1
        %search nearest point index
        for i=1:size(repos,1)
            %d(i)=sqrt((curpos(1,1)-repos(i,1))^2+(curpos(1,2)-repos(i,2))^2)
           d(i)=norm(curpos(1,1:2)-repos(i,1:2));
        end   
           [min_d ind]=min(d);
           old_nearest_point_index=ind;
    %else
       %  ind = old_nearest_point_index;
        % distance_this_index = norm(curpos(1,1:2)-repos(ind,1:2));
        %while true
            %    if (ind + 1) < size(repos,1) 
                    ind = ind + 1 ;   
            %    else 
            %         ind=ind;
             %   end
               % distance_next_index=norm(curpos(1,1:2)-repos(ind,1:2));
                %if distance_this_index < distance_next_index  
               %       break;
               % end
             %   distance_this_index = distance_next_index;
     %   end
    %    old_nearest_point_index = ind;
       % disp("caokaifa");
   % end
    L = 0.0;
    k=0.1;
    v=0.5;
    Lfc=lookdistance;
    Lf =0.3;
    % search look ahead target point index
    while Lf > L && (ind + 1) < size(repos,1)
        
        L = norm(curpos(1,1:2)-repos(ind,1:2))
        ind =ind+1
        %disp("%d",ind)
    end
   
f = repos(ind,1:2);
y=f';
old_nearest_point_indexnew=cast(old_nearest_point_index, 'like', curpos);
Pure Pursuit两部分组成,计算lateralErr和PID控制转换为steerCmd:

注意,这里的matlab程序我是在maltab2019a环境下运行的,如果下载的代码不能运行,请更新maltab为2019a,破解版网上好多,这里就不介绍了。maltab代码下载地址:

https://download.csdn.net/download/caokaifa/11233981

python代码下载直接上面复制粘贴就可以运行



所属网站分类: 技术文章 > 博客

作者:mimi

链接:https://www.pythonheidong.com/blog/article/7649/a5989f4bfeb6c7eaedb8/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)