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个waypointwaypoints = 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.locationlocation.z = 1ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)breakreturn 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().locationlocation2 = ego_vehicle.get_transform().locationrel_x = location1.x - location2.xrel_y = location1.y - location2.ydistance = math.sqrt(rel_x * rel_x + rel_y * rel_y)print("relative dis",distance)#rel_x 大于等于0,说明目标车在前方if rel_x >= 0:distance = distanceelse:distance = -distanceif distance >= dis_to_cut:print("The conditions for changing lanes are met.")cut_in_flag = Trueelse:cut_in_flag = Falsereturn 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车辆当前所在的waypointcurrent_location = vehicle.get_transform().locationcurrent_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.0brake = 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_speedclass 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 = Truesettings.fixed_delta_seconds = 0.05def 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_vehicledef spawn_npc_by_offset(self,ego_spawn_point,offset):vehicle_bp = self.world.get_blueprint_library().filter('vehicle.tesla.*')[0]# 计算新的生成点rotation = ego_spawn_point.rotationlocation = ego_spawn_point.locationlocation.x += offset.xlocation.y += offset.ylocation.z += offset.znpc_transform = carla.Transform(location, rotation)npc_vehicle = self.world.spawn_actor(vehicle_bp, npc_transform)return npc_vehicledef get_spawn_point(self,target_road_id,target_lane_id):#每隔5m生成1个waypointwaypoints = 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.locationlocation.z = 1ego_spawn_point = carla.Transform(location, waypoint.transform.rotation)breakreturn ego_spawn_pointdef cal_target_route(self,vehicle=None,lanechange="left",target_dis=20):#实例化道路规划模块grp = GlobalRoutePlanner(self.map, 2)#获取npc车辆当前所在的waypointcurrent_location = vehicle.get_transform().locationcurrent_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 routedef 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.0brake = 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().locationlocation2 = ego_vehicle.get_transform().locationrel_x = location1.x - location2.xrel_y = location1.y - location2.ydistance = math.sqrt(rel_x * rel_x + rel_y * rel_y)print("relative dis",distance)if rel_x >= 0:distance = distanceelse:distance = -distanceif distance >= dis_to_cut:print("The conditions for changing lanes are met.")cut_in_flag = Trueelse:cut_in_flag = Falsereturn cut_in_flagif __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)#设置目标车初始速度的纵向控制PIDinitspd_pid = PIDLongitudinalController(npc_vehicle, K_P=1.0, K_I=0.1, K_D=0.05)#设置目标车的cut_in的横纵向控制PIDargs_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 = Nonewaypoint_index = 0need_cal_route = Truecut_in_flag = Falsearrive_target_point = Falsetarget_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/htarget_speed = ego_speed + 8 #目标车的目标速度#是否满足cut_in条件if cut_in_flag:if need_cal_route:#生成车侧车道前方30m的waypointwaypoints = 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 = Trueprint("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 incut_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.hqwc.cn/news/505473.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Docker容器资源限制与优化全攻略:CPU、内存、磁盘IO一网打尽

&#x1f407;明明跟你说过&#xff1a;个人主页 &#x1f3c5;个人专栏&#xff1a;《Docker入门到精通》 《k8s入门到实战》&#x1f3c5; &#x1f516;行路有良友&#xff0c;便是天堂&#x1f516; 目录 一、引言 1、docker容器技术概述 2、资源限制与优化的重要性 …

C++设计模式_创建型模式_工厂方法模式

目录 C设计模式_创建型模式_工厂方法模式 一、简单工厂模式 1.1 简单工厂模式引入 1.2 简单工厂模式 1.3 简单工厂模式利弊分析 1.4 简单工厂模式的UML图 二、工厂方法模式 2.1 工厂模式和简单工厂模式比较 2.2 工厂模式代码实现 2.3 工厂模式UML 三、抽象工厂模式 3.1 战斗场景…

IDEA的安装教程

1、下载软件安装包 官网下载&#xff1a;https://www.jetbrains.com/idea/ 2、开始安装IDEA软件 解压安装包&#xff0c;找到对应的idea可执行文件&#xff0c;右键选择以管理员身份运行&#xff0c;执行安装操作 3、运行之后&#xff0c;点击NEXT&#xff0c;进入下一步 4、…

RISC-V特权架构 - 特权模式与指令

RV32/64 特权架构 - 特权模式与指令 1 特权模式2 特权指令2.1 mret&#xff08;从机器模式返回到先前的模式&#xff09;2.2 sret&#xff08;从监管模式返回到先前的模式&#xff09;2.3 wfi&#xff08;等待中断&#xff09;2.4 sfence.vma&#xff08;内存屏障&#xff09; …

官宣 | 凯琦供应链成为亚马逊SPN物流服务商!

再播一条喜讯&#xff01;在亚马逊官方平台的筛选考核下&#xff0c;凯琦供应链近日正式入驻亚马逊SPN服务商平台&#xff0c;成为亚马逊SPN第三方承运商。 这也标志着凯琦9年来在FBA物流领域的服务质量得到了客户、官方及行业的广泛认可&#xff0c;未来凯琦将继续为亚马逊卖家…

【LeetCode题解】2182. 构造限制重复的字符串+82. 删除排序链表中的重复元素 II+83. 删除排序链表中的重复元素

文章目录 [2182. 构造限制重复的字符串](https://leetcode.cn/problems/construct-string-with-repeat-limit/)思路&#xff1a; [82. 删除排序链表中的重复元素 II](https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/)[83. 删除排序链表中的重复元素](htt…

swoole

php是单线程。php是靠多进程来处理任务&#xff0c;任何后端语言都可以采用多进程处理方式。如我们常用的php-fpm进程管理器。线程与协程,大小的关系是进程>线程>协程,而我们所说的swoole让php实现了多线程,其实在这里来说,就是好比让php创建了多个进程,每个进程执行一条…

前端学习第六天-css浮动和定位

达标要求 了解浮动的意义 掌握浮动的样式属性 熟练应用清除浮动 熟练掌握定位的三种方式 能够说出网页布局的不同方式的意义 1. 浮动(float) 1.1 CSS 布局的三种机制 网页布局的核心——就是用 CSS 来摆放盒子。CSS 提供了 3 种机制来设置盒子的摆放位置&#xff0c;分…

基于原子变量的内存模型优化

概述 线程间同步通常的实现方法通常为互斥锁&#xff0c;但互斥锁对性能造成了影响&#xff0c;C11引入了内存模型&#xff0c;定义了STD::memory_order枚举&#xff0c;结合原子性操作&#xff0c;实现无锁线程数据同步。 关于memory_order memory_order_relaxed&#xff1…

前端打包部署(黑马学习笔记)

我们的前端工程开发好了&#xff0c;但是我们需要发布&#xff0c;那么如何发布呢&#xff1f;主要分为2步&#xff1a; 1.前端工程打包 2.通过nginx服务器发布前端工程 前端工程打包 接下来我们先来对前端工程进行打包 我们直接通过VS Code的NPM脚本中提供的build按钮来完…

逻辑漏洞(pikachu)

#水平&#xff0c;垂直越权&#xff0c;未授权访问 通过个更换某个id之类的身份标识&#xff0c;从而使A账号获取&#xff08;修改、删除&#xff09;B账号数据 使用低权限身份的账号&#xff0c;发送高权限账号才能有的请求&#xff0c;获得其高权限操作 通过删除请求中的认…

Linux查看进程和线程

根据PID查看进程 查找到进程的PID&#xff0c;以查看端口占用为例 lsof -i:8080 根据PID查看进程信息 lsof -p 5807或ll /proc/5807/ /proc/5807/目录下部分子目录说明 cwd 进程运行目录 exe 执行程序的绝对路径 cmdline 程序运行时输入的命令行命令 environ 记录了进程运行…