Carla自动驾驶仿真九:车辆变道路径规划

文章目录

  • 前言
  • 一、关键函数
  • 二、完整代码
  • 效果


前言

本文介绍一种在carla中比较简单的变道路径规划方法,主要核心是调用carla的GlobalRoutePlanner模块和PID控制模块实现变道,大体的框架如下图所示。

在这里插入图片描述

在这里插入图片描述


一、关键函数

1、get_spawn_point(),该函数根据指定road和lane获得waypoint(这里之所以这么用是为了选择一条比较长的直路)。具体用法可以参考上篇文章:Carla自动驾驶仿真八:两种查找CARLA地图坐标点的方法

def get_spawn_point(self,target_road_id,target_lane_id):
    #每隔5m生成1个waypoint
    waypoints = self.map.generate_waypoints(5.0)
    # 遍历路点
    for waypoint in waypoints:
        if waypoint.road_id == target_road_id:
            lane_id = waypoint.lane_id
            # 检查是否已经找到了特定车道ID的路点
            if lane_id == target_lane_id:
                location = waypoint.transform.location
                location.z = 1
                ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)
                break
    return ego_spawn_point

2、should_cut_in(),用于主车和目标车的相对距离判断,当目标车超越自车一定距离时,开始给cut_in_flag置Ture,并在下一步骤规划变道路径和执行变道操作。

 def should_cut_in(self,npc_vehicle, ego_vehicle, dis_to_cut=5):
     location1 = npc_vehicle.get_transform().location
     location2 = ego_vehicle.get_transform().location
     rel_x = location1.x - location2.x
     rel_y = location1.y - location2.y
     distance = math.sqrt(rel_x * rel_x + rel_y * rel_y)
     print("relative dis",distance)
     #rel_x 大于等于0,说明目标车在前方
     if rel_x >= 0:
         distance = distance
     else:
         distance = -distance
     if distance >= dis_to_cut:
         print("The conditions for changing lanes are met.")
         cut_in_flag = True
     else:
         cut_in_flag = False
     return cut_in_flag

3、cal_target_route(),函数中调用了Carla的GlobalRoutePlanner模块,能根据起点和终点自动生成车辆行驶的路径(重点),我这里的变道起点是两车相对距离达到(阈值)时目标车的当前位置,而终点就是左侧车道前方target_dis米。将起点和终点代入到route = grp.trace_route(current_location, target_location)就能获取到规划路径route

在这里插入图片描述

 def cal_target_route(self,vehicle=None,lanechange="left",target_dis=20):
     #实例化道路规划模块
     grp = GlobalRoutePlanner(self.map, 2)
     #获取npc车辆当前所在的waypoint
     current_location = vehicle.get_transform().location
     current_waypoint = self.map.get_waypoint(current_location)
     #选择变道方向
     if "left" in lanechange:
         target_org_waypoint = current_waypoint.get_left_lane()
     elif "right" in lanechange:
         target_org_waypoint = current_waypoint.get_right_lane()
     #获取终点的位置
     target_location = target_org_waypoint.next(target_dis)[0].transform.location
     #根据起点和重点生成规划路径
     route = grp.trace_route(current_location, target_location)

     return route

4、speed_con_by_pid(),通过PID控制车辆的达到目标速度,pid是通过实例化Carla的PIDLongitudinalController实现。由于pid.run_step()只返回油门的控制,需要增加刹车的逻辑。

 control_signal = pid.run_step(target_speed=target_speed, debug=False)
 throttle = max(min(control_signal, 1.0), 0.0)  # 确保油门值在0到1之间
 brake = 0.0  # 根据需要设置刹车值
 if control_signal < 0:
     throttle = 0.0
     brake = abs(control_signal)  # 假设控制器输出的负值可以用来刹车
 vehilce.apply_control(carla.VehicleControl(throttle=throttle, brake=brake))

5、PID = VehiclePIDController()是carla的pid横纵向控制模块,通过设置目标速度和目标终点来实现轨迹控制control = PID.run_step(target_speed, target_waypoint),PID参数我随便调了一组,有兴趣的可以深入调一下。


二、完整代码

import carla
import time
import math
import sys

#修改成自己的carla路径
sys.path.append(r'D:\CARLA_0.9.14\WindowsNoEditor\PythonAPI\carla')
from agents.navigation.global_route_planner import GlobalRoutePlanner
from agents.navigation.controller import VehiclePIDController,PIDLongitudinalController
from agents.tools.misc import draw_waypoints, distance_vehicle, vector, is_within_distance, get_speed


class CarlaWorld:
    def __init__(self):
        self.client = carla.Client('localhost', 2000)
        self.world = self.client.load_world('Town06')
        # self.world = self.client.get_world()
        self.map = self.world.get_map()
        # 开启同步模式
        settings = self.world.get_settings()
        settings.synchronous_mode = True
        settings.fixed_delta_seconds = 0.05

    def spawm_ego_by_point(self,ego_spawn_point):
        vehicle_bp = self.world.get_blueprint_library().filter('vehicle.tesla.*')[0]
        ego_vehicle = self.world.try_spawn_actor(vehicle_bp,ego_spawn_point)

        return ego_vehicle

    def spawn_npc_by_offset(self,ego_spawn_point,offset):
        vehicle_bp = self.world.get_blueprint_library().filter('vehicle.tesla.*')[0]
        # 计算新的生成点
        rotation = ego_spawn_point.rotation
        location = ego_spawn_point.location
        location.x += offset.x
        location.y += offset.y
        location.z += offset.z
        npc_transform = carla.Transform(location, rotation)
        npc_vehicle = self.world.spawn_actor(vehicle_bp, npc_transform)

        return npc_vehicle

    def get_spawn_point(self,target_road_id,target_lane_id):
        #每隔5m生成1个waypoint
        waypoints = self.map.generate_waypoints(5.0)
        # 遍历路点
        for waypoint in waypoints:
            if waypoint.road_id == target_road_id:
                lane_id = waypoint.lane_id
                # 检查是否已经找到了特定车道ID的路点
                if lane_id == target_lane_id:
                    location = waypoint.transform.location
                    location.z = 1
                    ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)
                    break
        return ego_spawn_point
    
    def cal_target_route(self,vehicle=None,lanechange="left",target_dis=20):
        #实例化道路规划模块
        grp = GlobalRoutePlanner(self.map, 2)
        #获取npc车辆当前所在的waypoint
        current_location = vehicle.get_transform().location
        current_waypoint = self.map.get_waypoint(current_location)
        #选择变道方向
        if "left" in lanechange:
            target_org_waypoint = current_waypoint.get_left_lane()
        elif "right" in lanechange:
            target_org_waypoint = current_waypoint.get_right_lane()
        #获取终点的位置
        target_location = target_org_waypoint.next(target_dis)[0].transform.location
        #根据起点和重点生成规划路径
        route = grp.trace_route(current_location, target_location)

        return route

    def draw_target_line(self,waypoints):
        # 获取世界和调试助手
        debug = self.world.debug
        # 设置绘制参数
        life_time = 60.0  # 点和线将持续显示的时间(秒)
        color = carla.Color(255, 0, 0)
        thickness = 0.3  # 线的厚度
        for i in range(len(waypoints) - 1):
            debug.draw_line(waypoints[i][0].transform.location + carla.Location(z=0.5),
                            waypoints[i + 1][0].transform.location + carla.Location(z=0.5),
                            thickness=thickness,
                            color=color,
                            life_time=life_time)

    def draw_current_point(self,current_point):
        self.world.debug.draw_point(current_point,size=0.1, color=carla.Color(b=255), life_time=60)

    def speed_con_by_pid(self,vehilce=None,pid=None,target_speed=30):
        control_signal = pid.run_step(target_speed=target_speed, debug=False)
        throttle = max(min(control_signal, 1.0), 0.0)  # 确保油门值在0到1之间
        brake = 0.0  # 根据需要设置刹车值
        if control_signal < 0:
            throttle = 0.0
            brake = abs(control_signal)  # 假设控制器输出的负值可以用来刹车
        vehilce.apply_control(carla.VehicleControl(throttle=throttle, brake=brake))

    def set_spectator(self,vehicle):
        self.world.get_spectator().set_transform(
            carla.Transform(vehicle.get_transform().location +
            carla.Location(z=50), carla.Rotation(pitch=-90))
        )

    def should_cut_in(self,npc_vehicle, ego_vehicle, dis_to_cut=5):
        location1 = npc_vehicle.get_transform().location
        location2 = ego_vehicle.get_transform().location
        rel_x = location1.x - location2.x
        rel_y = location1.y - location2.y
        distance = math.sqrt(rel_x * rel_x + rel_y * rel_y)
        print("relative dis",distance)
        if rel_x >= 0:
            distance = distance
        else:
            distance = -distance
        if distance >= dis_to_cut:
            print("The conditions for changing lanes are met.")
            cut_in_flag = True
        else:
            cut_in_flag = False
        return cut_in_flag


if __name__ == '__main__':
    try:
        CARLA = CarlaWorld()
        #根据road_id和lane_id选择出生点
        start_point = CARLA.get_spawn_point(target_road_id=40, target_lane_id=-5)

        #生成自车
        ego_vehicle = CARLA.spawm_ego_by_point(start_point)

        #设置初始的观察者视角
        CARLA.set_spectator(ego_vehicle)

        #相对ego生成目标车
        relative_ego = carla.Location(x=-10, y=3.75, z=0)
        npc_vehicle = CARLA.spawn_npc_by_offset(start_point, relative_ego)

        # 设置ego自动巡航
        ego_vehicle.set_autopilot(True)

        #设置目标车初始速度的纵向控制PID
        initspd_pid = PIDLongitudinalController(npc_vehicle, K_P=1.0, K_I=0.1, K_D=0.05)

        #设置目标车的cut_in的横纵向控制PID
        args_lateral_dict = {'K_P': 0.8, 'K_D': 0.8, 'K_I': 0.70, 'dt': 1.0 / 10.0}
        args_long_dict = {'K_P': 1, 'K_D': 0.0, 'K_I': 0.75, 'dt': 1.0 / 10.0}
        PID = VehiclePIDController(npc_vehicle, args_lateral_dict, args_long_dict)

        waypoints = None
        waypoint_index = 0
        need_cal_route = True
        cut_in_flag = False
        arrive_target_point = False
        target_distance_threshold = 2.0  # 切换waypoint的距离
        start_sim_time = time.time()
        while not arrive_target_point:
            CARLA.world.tick()
            # 更新观察者的视野
            CARLA.set_spectator(ego_vehicle)
            #计算目标车的初始速度
            ego_speed = (ego_vehicle.get_velocity().x  * 3.6) #km/h
            target_speed = ego_speed + 8 #目标车的目标速度
            #是否满足cut_in条件
            if cut_in_flag:
                if need_cal_route:
                    #生成车侧车道前方30m的waypoint
                    waypoints = CARLA.cal_target_route(npc_vehicle,lanechange= "left",target_dis=30)
                    CARLA.draw_target_line(waypoints)
                    need_cal_route = False

                # 如果已经计算了路线
                if waypoints is not None and waypoint_index < len(waypoints):
                    # 获取当前目标路点
                    target_waypoint = waypoints[waypoint_index][0]
                    # 获取车辆当前位置
                    transform = npc_vehicle.get_transform()
                    #绘制当前运行的点
                    CARLA.draw_current_point(transform.location)
                    # 计算车辆与当前目标路点的距离
                    distance_to_waypoint = distance_vehicle(target_waypoint, transform)
                    # 如果车辆距离当前路点的距离小于阈值,则更新到下一个路点
                    if distance_to_waypoint < target_distance_threshold:
                        waypoint_index += 1  # 移动到下一个路点
                        if waypoint_index >= len(waypoints):
                            arrive_target_point = True
                            print("npc_vehicle had arrive target point.")
                            break  # 如果没有更多的路点,退出循环
                    else:
                        # 计算控制命令
                        control = PID.run_step(target_speed, target_waypoint)
                        # 应用控制命令
                        npc_vehicle.apply_control(control)
            else:
                #设置NPC的初始速度
                CARLA.speed_con_by_pid(npc_vehicle,initspd_pid,target_speed)
                #判断是否可以cut in
                cut_in_flag = CARLA.should_cut_in(npc_vehicle,ego_vehicle,dis_to_cut=8)

            # 判断是否达到模拟时长
            if time.time() - start_sim_time > 60:
                print("Simulation ended due to time limit.")
                break

        #到达目的地停车
        npc_vehicle.apply_control(carla.VehicleControl(throttle=0, steer=0, brake=-0.5))
        print("Control the target car to brake.")
        time.sleep(10)
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # 清理资源
        print("Cleaning up the simulation...")
        if ego_vehicle is not None:
            ego_vehicle.destroy()
        if npc_vehicle is not None:
            npc_vehicle.destroy()
        settings = CARLA.world.get_settings()
        settings.synchronous_mode = False  # 禁用同步模式
        settings.fixed_delta_seconds = None

效果

下述是变道规划简单的实现,轨迹跟踪效果比较一般,PID没有仔细调,紫色是车辆运行的点迹。

在这里插入图片描述
公众号:自动驾驶simulation

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/423215.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

如何查看docker容器里面运行的nginx的配置文件哪

要查看Docker容器内运行的Nginx配置文件的位置&#xff0c;你可以通过进入容器的shell环境来直接查看。Nginx的默认配置文件通常位于/etc/nginx/nginx.conf&#xff0c;而网站特定的配置文件通常位于/etc/nginx/conf.d/目录中。以下是步骤来查看这些配置文件&#xff1a; 步骤…

【嵌入式学习】网络编程day0229

一、思维导图 二、练习 TCP通信 服务器 #include <myhead.h> #define SER_IP "192.168.126.42" #define SER_PORT 8888 int main(int argc, const char *argv[]) {int wfd-1;//创建套接字if((wfdsocket(AF_INET,SOCK_STREAM,0))-1){perror("error"…

基于CNN-LSTM-Attention的时间序列回归预测matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1卷积神经网络&#xff08;CNN&#xff09;在时间序列中的应用 4.2 长短时记忆网络&#xff08;LSTM&#xff09;处理序列依赖关系 4.3 注意力机制&#xff08;Attention&#xff09; 5…

探索数据结构:深入了解顺序表的奥秘

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ &#x1f388;&#x1f388;养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; 所属专栏&#xff1a;数据结构与算法 贝蒂的主页&#xff1a;Betty’s blog 1. 什么是顺序表 顺序表是用一段物理地址连续的存储单元依次存储数据元…

迪杰斯特拉算法的具体应用

fill与memset的区别介绍 例一 #include <iostream> #include <algorithm> using namespace std; const int maxn500; const int INF1000000000; bool isin[maxn]{false}; int G[maxn][maxn]; int path[maxn],rescue[maxn],num[maxn]; int weight[maxn]; int cityn…

011 Linux_线程概念与创建

前言 本文将会向你介绍线程的概念&#xff0c;以及线程是怎么被创建的 线程概念 一、进程是承担系统资源的基本实体&#xff0c;线程是cpu调度的基本单位 首先&#xff0c;地址空间在逻辑上相当于进程的资源窗口&#xff0c; 每个进程都有这样一个资源窗口。通过地址空间页…

《热辣滚烫》:用坚持不懈开启逆境中的职场出路

"你只活一次&#xff0c;所以被嘲笑也没有关系&#xff0c;想哭也没有关系&#xff0c;失败更没有关系。" “人生就像一场拳击赛&#xff0c;你站不起来&#xff0c;就永远不知道自己有多强” “命运只负责洗牌&#xff0c;出牌的永远是自己。” 在今年的贺岁档电影市…

MySQL的21个SQL经验

1. 写完SQL先explain查看执行计划(SQL性能优化) 日常开发写SQL的时候,尽量养成这个好习惯呀:写完SQL后,用explain分析一下,尤其注意走不走索引。 explain select userid,name,age from user where userid =10086 or age =18;2、操作delete或者update语句,加个limit(S…

C++之stack

1、stack简介 stack是实现的一个先进后出&#xff0c;后进先出的容器。它只有一个出口&#xff0c;只能操作最顶端元素。 2、stack库函数 &#xff08;1&#xff09;push() //向栈压入一个元素 &#xff08;2&#xff09;pop() //移除栈顶元素 &#xff08;3…

IO多路转接

1.select 初识select 系统提供 select 函数来实现多路复用输入 / 输出模型 . select 系统调用是用来让我们的程序监视多个文件描述符的状态变化的 ; 程序会停在 select 这里等待&#xff0c;直到被监视的文件描述符有一个或多个发生了状态改变 ; select函数模型 select的函…

LaTeX-设置表格大小

文章目录 LaTeX-设置表格大小1.创建表格2.设置表格的宽度2.1控制表格每一列的宽度2.2控制整个表格的宽度 3.设置表格的外观4.LaTeX绘制三线表 LaTeX-设置表格大小 本文介绍了LaTeX如何设置表格的大小、改变表格的外观以及如何绘制三线表。 1.创建表格 在LaTeX中创建表很耗时…

RocketMQ学习笔记一

课程来源&#xff1a;002-MQ简介_哔哩哔哩_bilibili &#xff08;尚硅谷老雷&#xff0c;时长19h&#xff09; 第1章 RocketMQ概述 1. MQ是什么&#xff1f; 2. MQ用途有哪些&#xff1f; 限流削峰&#xff1b;异步解耦&#xff1b;数据收集。 3. 常见MQ产品有哪些&对比…

10-Java装饰器模式 ( Decorator Pattern )

Java装饰器模式 摘要实现范例 装饰器模式&#xff08;Decorator Pattern&#xff09;允许向一个现有的对象添加新的功能&#xff0c;同时又不改变其结构 装饰器模式创建了一个装饰类&#xff0c;用来包装原有的类&#xff0c;并在保持类方法签名完整性的前提下&#xff0c;提供…

测试/测试开发八股——找大厂测试实习基础篇

第一部分:基础概念 1. 软件测试是什么? 在规定的条件下对一个产品或者程序进行操作,以发现程序错误,衡量软件质量,并对其是否能满足设计要求进行评估的过程。 软件测试工程师的任务 2. 软件测试工程师的任务 软件测试工程师主要工作是检查软件是否有bug、是否具有稳定…

【深度学习笔记】计算机视觉——图像增广

图像增广 sec_alexnet提到过大型数据集是成功应用深度神经网络的先决条件。 图像增广在对训练图像进行一系列的随机变化之后&#xff0c;生成相似但不同的训练样本&#xff0c;从而扩大了训练集的规模。 此外&#xff0c;应用图像增广的原因是&#xff0c;随机改变训练样本可以…

Spring对IoC的实现

个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名大三在校生&#xff0c;喜欢AI编程&#x1f38b; &#x1f43b;‍❄️个人主页&#x1f947;&#xff1a;落798. &#x1f43c;个人WeChat&#xff1a;hmmwx53 &#x1f54a;️系列专栏&#xff1a;&#x1f5bc;️…

GO-并发

1. 并发 有人把Go语言比作 21 世纪的C语言&#xff0c;第一是因为Go语言设计简单&#xff0c;第二则是因为 21 世纪最重要的就是并发程序设计&#xff0c;而 Go 从语言层面就支持并发。同时实现了自动垃圾回收机制。 先来了解一些概念&#xff1a; 进程/线程 进程是程序在操…

Bootstrap的使用

目录 js的引入&#xff1a; 1.行内式 2.嵌入式 3.外链式 Bootstrap:的引入 注意事项&#xff1a; 条件注释语句&#xff1a; 栅格系统&#xff1a; 列嵌套&#xff1a; 列偏移&#xff1a; 列排序&#xff1a; 响应式工具&#xff1a; Bootstrap的字体图标的使用&a…

探讨苹果 Vision Pro 的 AI 数字人形象问题

Personas 的设计模糊性&#xff1a; 部分人认为这种模糊设计可能是出于安全考虑&#x1f6e1;️。安全角度&#xff1a;Personas 代表着你的 AI 数字形象&#xff0c;在创建时&#xff0c;它相当于你的 AVP&#xff08;生物识别扫描器的存在增加了冒充的难度&#xff09;。如果…

mysql服务治理

一、性能监控指标和解决方案 1.QPS 一台 MySQL 数据库&#xff0c;大致处理能力的极限是&#xff0c;每秒一万条左右的简单 SQL&#xff0c;这里的“简单 SQL”&#xff0c;指的是类似于主键查询这种不需要遍历很多条记录的 SQL。 根据服务器的配置高低&#xff0c;可能低端…
最新文章