解析apollo纵向控制标定表程序

2024-09-08 09:18

本文主要是介绍解析apollo纵向控制标定表程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

百度apollo采用标定表描述车辆速度、加速度与油门/刹车之间的关系。该表可使无人车根据当前车速与期望加速度得到合适的油门/刹车开合度。除了文献《Baidu Apollo Auto-Calibration System - An Industry-Level Data-Driven and Learning based Vehicle Longitude Dynamic Calibrating Algorithm》给出的离线与在线标定方法,百度在apollo 3.0版本及更早版本的apollo/modules/tools/calibration中给出了人工标定的程序,可生成该标定表。现将代码进行解释说明。

一、工程目录

打开apollo/modules/tools/calibration,文件目录如下图所示:
在这里插入图片描述
其中,关键的几个程序为:data_collector.pyprocess_data.pyprocess.pydata_collector.py采集底盘的反馈信息,并保存文件。process_data.pyprocess.py对采信的数据进行处理得到最终的标定表。

二、数据采集

### data_collector.py ####
import os
import sys
import time
import signalimport rospy
from std_msgs.msg import Stringfrom plot_data import Plotterfrom modules.canbus.proto import chassis_pb2
from modules.control.proto import control_cmd_pb2
from modules.localization.proto import localization_pb2class DataCollector(object):"""DataCollector Class"""def __init__(self):self.sequence_num = 0self.control_pub = rospy.Publisher('/apollo/control', control_cmd_pb2.ControlCommand, queue_size=1)rospy.sleep(0.3)self.controlcmd = control_cmd_pb2.ControlCommand()self.canmsg_received = Falseself.localization_received = Falseself.case = 'a'self.in_session = Falseself.outfile = ""def run(self, cmd):signal.signal(signal.SIGINT, self.signal_handler)# 根据加速度、速度限制、减速度等信息得到将要保存的文件名self.in_session = Trueself.cmd = map(float, cmd)out = ''if self.cmd[0] > 0:out = out + 't'else:out = out + 'b'out = out + str(int(self.cmd[0]))if self.cmd[2] > 0:out = out + 't'else:out = out + 'b'out = out + str(int(self.cmd[2])) + 'r'i = 0self.outfile = out + str(i) + '_recorded.csv'# 得到一个未存在的新文件名while os.path.exists(self.outfile):i += 1self.outfile = out + str(i) + '_recorded.csv'self.file = open(self.outfile, 'w')self.file.write("time,io,ctlmode,ctlbrake,ctlthrottle,ctlgear_location,vehicle_speed,"+"engine_rpm,driving_mode,throttle_percentage,brake_percentage,gear_location, imu\n") # 保存的数据头 print "Send Reset Command"self.controlcmd.header.module_name = "control"self.controlcmd.header.sequence_num = self.sequence_numself.sequence_num = self.sequence_num + 1self.controlcmd.header.timestamp_sec = rospy.get_time()self.controlcmd.pad_msg.action = 2self.control_pub.publish(self.controlcmd)rospy.sleep(0.2)# Set Default Messageprint "Send Default Command"self.controlcmd.pad_msg.action = 1self.controlcmd.throttle = 0self.controlcmd.brake = 0self.controlcmd.steering_rate = 100self.controlcmd.steering_target = 0self.controlcmd.gear_location = chassis_pb2.Chassis.GEAR_DRIVEself.canmsg_received = Falserate = rospy.Rate(100)while self.in_session:self.publish_control() # 进入到发送控制命令函数rate.sleep()def signal_handler(self, signal, frame):self.in_session = Falsedef callback_localization(self, data):"""New Localization"""self.acceleration = data.pose.linear_acceleration_vrf.yself.localization_received = Truedef callback_canbus(self, data):"""New CANBUS"""if not self.localization_received:print "No Localization Message Yet"returntimenow = data.header.timestamp_secself.vehicle_speed = data.speed_mpsself.engine_rpm = data.engine_rpmself.throttle_percentage = data.throttle_percentageself.brake_percentage = data.brake_percentageself.gear_location = data.gear_locationself.driving_mode = data.driving_modeself.canmsg_received = Trueif self.in_session:self.write_file(timenow, 0)  # 记录一组数据,该数据标记为0,在处理阶段被使用来生成标定表def publish_control(self):"""New Control Command"""if not self.canmsg_received:print "No CAN Message Yet"returnself.controlcmd.header.sequence_num = self.sequence_numself.sequence_num = self.sequence_num + 1if self.case == 'a':if self.cmd[0] > 0:self.controlcmd.throttle = self.cmd[0]self.controlcmd.brake = 0else:self.controlcmd.throttle = 0self.controlcmd.brake = -self.cmd[0]if self.vehicle_speed >= self.cmd[1]:self.case = 'd'elif self.case == 'd':if self.cmd[2] > 0:self.controlcmd.throttle = self.cmd[0]self.controlcmd.brake = 0else:self.controlcmd.throttle = 0self.controlcmd.brake = -self.cmd[2]if self.vehicle_speed == 0:self.in_session = Falseself.controlcmd.header.timestamp_sec = rospy.get_time()self.control_pub.publish(self.controlcmd)self.write_file(self.controlcmd.header.timestamp_sec, 1)  # 此处记录的数据,标记为1,在处理阶段未使用if self.in_session == False:self.file.close()def write_file(self, time, io):"""Write Message to File"""self.file.write("%.4f,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" %(time, io, 1, self.controlcmd.brake, self.controlcmd.throttle,self.controlcmd.gear_location, self.vehicle_speed, self.engine_rpm,self.driving_mode, self.throttle_percentage, self.brake_percentage,self.gear_location, self.acceleration))  # 记录的数据def main():"""Main function"""rospy.init_node('data_collector', anonymous=True)data_collector = DataCollector()plotter = Plotter()localizationsub = rospy.Subscriber('/apollo/localization/pose',localization_pb2.LocalizationEstimate,data_collector.callback_localization)canbussub = rospy.Subscriber('/apollo/canbus/chassis', chassis_pb2.Chassis,data_collector.callback_canbus)print "Enter q to quit"print "Enter p to plot result from last run"print "Enter x to remove result from last run"print "Enter x y z, where x is acceleration command, y is speed limit, z is decceleration command"print "Positive number for throttle and negative number for brake"# 命令行输入指定,程序按指定执行特定操作,当输入的个数为3时,也即包含{加速度,速度限制,减速度}等信息while True:cmd = raw_input("Enter commands: ").split()if len(cmd) == 0:print "Quiting"breakelif len(cmd) == 1:if cmd[0] == "q":breakelif cmd[0] == "p":print "Plotting result"if os.path.exists(data_collector.outfile):plotter.process_data(data_collector.outfile)plotter.plot_result()else:print "File does not exist"elif cmd[0] == "x":print "Removing last result"if os.path.exists(data_collector.outfile):os.remove(data_collector.outfile)else:print "File does not exist"elif len(cmd) == 3:data_collector.run(cmd) # 进入数据采集主要程序if __name__ == '__main__':main()

三、数据处理,生成标定表

###  process_data.py  ####
import math
import sysimport numpy as np
import tkFileDialogfrom process import get_start_index
from process import preprocess
from process import processclass Plotter(object):"""plot the speed info"""def __init__(self, filename):"""init the speed info"""np.set_printoptions(precision=3)self.file = open('result.csv', 'a')self.file_one = open(filename + ".result", 'w')def process_data(self, filename):"""load the file and preprocess th data"""self.data = preprocess(filename)  # 预处理self.tablecmd, self.tablespeed, self.tableacc, self.speedsection, self.accsection, self.timesection = process(self.data) #核心处理程序def save_data(self):""""""for i in range(len(self.tablecmd)):for j in range(len(self.tablespeed[i])):self.file.write("%s, %s, %s\n" %(self.tablecmd[i], self.tablespeed[i][j],self.tableacc[i][j]))self.file_one.write("%s, %s, %s\n" %(self.tablecmd[i], self.tablespeed[i][j],self.tableacc[i][j]))def main():"""demo"""if len(sys.argv) == 2:# get the latest filefile_path = sys.argv[1]else:file_path = tkFileDialog.askopenfilename(initialdir="/home/caros/.ros",filetypes=(("csv files", ".csv"), ("all files", "*.*")))plotter = Plotter(file_path)plotter.process_data(file_path)plotter.save_data()print 'save result to:', file_path + ".result"if __name__ == '__main__':main()

3.1 预处理

import math
import warningsimport numpy as np
import scipy.signal as signalwarnings.simplefilter('ignore', np.RankWarning)SPEED_INTERVAL = 0.2
SPEED_DELAY = 130  #Speed report delay relative to IMU informationdef preprocess(filename):data = np.genfromtxt(filename, delimiter=',', names=True)data = data[np.where(data['io'] == 0)[0]]data = data[np.argsort(data['time'])]data['time'] = data['time'] - data['time'][get_start_index(data)]b, a = signal.butter(6, 0.05, 'low')  # 低通滤波,去除数据中的噪声,由于采集频率为100HZ,此处表示留下频率为10HZ的信号,去除高频噪声。data['imu'] = signal.filtfilt(b, a, data['imu'])data['imu'] = np.append(data['imu'][-SPEED_DELAY / 10:],data['imu'][0:-SPEED_DELAY / 10]) return datadef get_start_index(data):if np.all(data['vehicle_speed'] == 0):return 0start_ind = np.where(data['vehicle_speed'] == 0)[0][0]ind = start_indwhile ind < len(data):if data['vehicle_speed'][ind] == 0:  ind = ind + 1# begin from vehicle_speed > 0 else:breakreturn ind
  • 数据对齐说明
    data['imu'] = np.append(data['imu'][-SPEED_DELAY / 10:],data['imu'][0:-SPEED_DELAY / 10]) 

有两种理解,分别为apollo的理解和我的理解。

apollo里的理解:

在给定油门/刹车开度得到加速度,但是速度是加速度与时间共同作用的结果。换句话说,与加速度对应的速度在未来。要把速度与加速度对齐,需要将加速度整体向后偏移一个时间常量,此处为 13 100 H Z s = 130 m s \frac{13}{100HZ}s=130ms 100HZ13s=130ms,与决策周期 100 m s 100ms 100ms非常接近。

我的理解与apollo的作法正好相反:

由于采集时,速度、加速度、油门/刹车的数据的时间戳是相同的。标定表能够工作的前提是,在速度一定下,给定确定的油门量或刹车量,能够得到确定的加速度。但是当前速度下,给定油门/刹车量,得到的加速度应该反应在未来时刻。因此,需要将加速度数据整体向前偏移一个时间常量

谁对谁错呢?

3.2 后处理

def process(data):"""process data"""np.set_printoptions(precision=3)if np.all(data['vehicle_speed'] == 0):print "All Speed = 0"return [], [], [], [], [], []start_index = get_start_index(data)#print "Start index: ", start_indexdata = data[start_index:]data['time'] = data['time'] - data['time'][0]# 得到单调加速段与单调减速段,因为在单调加速段,油门量相同,单调减速段,刹车量相同,便于批量处理。transition = np.where(np.logical_or(np.diff(data['ctlbrake']) != 0, np.diff(data['ctlthrottle']) != 0))[0]transition = np.insert(np.append(transition, len(data) - 1), 0, 0)#print "Transition indexes: ", transitionspeedsegments = []timesegments = []accsegments = []tablespeed = []tableacc = []tablecmd = []for i in range(len(transition) - 1):#print "process transition index:", data['time'][transition[i]], ":", data['time'][transition[i + 1]]speedsection = data['vehicle_speed'][transition[i]:transition[i +1] + 1]timesection = data['time'][transition[i]:transition[i + 1] + 1]brake = data['ctlbrake'][transition[i] + 1]throttle = data['ctlthrottle'][transition[i] + 1]imusection = data['imu'][transition[i]:transition[i + 1] + 1]if brake == 0 and throttle == 0:continue#print "Brake CMD: ", brake, " Throttle CMD: ", throttlefirstindex = 0while speedsection[firstindex] == 0:firstindex = firstindex + 1firstindex = max(firstindex - 2, 0)speedsection = speedsection[firstindex:]timesection = timesection[firstindex:]imusection = imusection[firstindex:]if speedsection[0] < speedsection[-1]:is_increase = Truelastindex = np.argmax(speedsection)else:is_increase = Falselastindex = np.argmin(speedsection)speedsection = speedsection[0:lastindex + 1]timesection = timesection[0:lastindex + 1]imusection = imusection[0:lastindex + 1]speedmin = np.min(speedsection)speedmax = np.max(speedsection)speedrange = np.arange(max(0, round(speedmin / SPEED_INTERVAL) * SPEED_INTERVAL),min(speedmax, 10.01), SPEED_INTERVAL)#print "Speed min, max", speedmin, speedmax, is_increase, firstindex, lastindex, speedsection[-1]accvalue = []# 对于给定速度,查询或插值得到对应的加速度数据。for value in speedrange:val_ind = 0if is_increase:while val_ind < len(speedsection) - 1 and value > speedsection[val_ind]:val_ind = val_ind + 1else:while val_ind < len(speedsection) - 1 and value < speedsection[val_ind]:val_ind = val_ind + 1if val_ind == 0:imu_value = imusection[val_ind]else:slope = (imusection[val_ind] - imusection[val_ind - 1]) / (speedsection[val_ind] - speedsection[val_ind - 1])imu_value = imusection[val_ind - 1] + slope * (value - speedsection[val_ind - 1])accvalue.append(imu_value)  if brake == 0:cmd = throttleelse:cmd = -brake#print "Overall CMD: ", cmd#print "Time: ", timesection#print "Speed: ", speedrange#print "Acc: ", accvalue#print cmdtablecmd.append(cmd)tablespeed.append(speedrange)tableacc.append(accvalue)speedsegments.append(speedsection)accsegments.append(imusection)timesegments.append(timesection)return tablecmd, tablespeed, tableacc, speedsegments, accsegments, timesegments

这篇关于解析apollo纵向控制标定表程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147704

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

Maven中生命周期深度解析与实战指南

《Maven中生命周期深度解析与实战指南》这篇文章主要为大家详细介绍了Maven生命周期实战指南,包含核心概念、阶段详解、SpringBoot特化场景及企业级实践建议,希望对大家有一定的帮助... 目录一、Maven 生命周期哲学二、default生命周期核心阶段详解(高频使用)三、clean生命周期核心阶

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

Java Scanner类解析与实战教程

《JavaScanner类解析与实战教程》JavaScanner类(java.util包)是文本输入解析工具,支持基本类型和字符串读取,基于Readable接口与正则分隔符实现,适用于控制台、文件输... 目录一、核心设计与工作原理1.底层依赖2.解析机制A.核心逻辑基于分隔符(delimiter)和模式匹

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装