找回密码
 会员注册
查看: 29|回复: 0

自动驾驶仿真:python和carsim联合仿真案例

[复制链接]

2万

主题

0

回帖

6万

积分

超级版主

积分
64113
发表于 2024-9-13 09:18:54 | 显示全部楼层 |阅读模式
文章目录前言一、Carsim官方案例二、Carsim配置1、车辆模型2、procedure配置3、RunControl配置三、python编写四、运行carsim五、运行python六、补充vs_solver.py代码总结前言carsim内部有许多相关联合仿真的demo,simulink、labview等等都有涉及,这里简单介绍下python和carsim联合仿真的方法,虽然carsim官方有个Steer_Control.py相关的案例,但是感觉比较冗余,这里抽出重点部分和大家交流探讨下。提示:以下是本篇文章正文内容,下面案例可供参考一、Carsim官方案例在carsim项目文件夹路径下,例:C:\ProgramFiles(x86)\CarSim2022.1_Data\Extensions\Custom_Py,里面有几个案例可以参考下。二、Carsim配置1、车辆模型1)这里的车辆模型随便选一个就行了2、procedure配置1)开环的节气门开度控制-油门2)开环的制动主缸压力控制-刹车3)开环的方向盘角度控制4)运行条件选择Runforver3、RunControl配置1)选择运行模型为:Self-ContainedSolvers2)选择类型为CWrapper,64-bit3)按照默认选择外部的解释器4)配置输入分别为:节气门开度,制动主缸压力,方向盘角度5)配置输出三、python编写1)第一步先找到vs_solver.py,用于调用simfile获取相关carsimdll的引用。vs_solver.py路径在C:\ProgramFiles(x86)\CarSim2022.1_Data\Extensions\Custom_Py,我们在下面代码中会引用vs_solver.py。2)代码部分都很简单,一个是importvs_solver,另外一个比较重要的是simfile的路径需要填写,一般在你创建项目目录下如:C:\ProgramFiles(x86)\CarSim2022.1_Data\simfile.sim,这个一定要根据你项目路径来填写。importosimportkeyboardimportctypesimportvs_solverclasscarsim_simulation():def__init__(self):self.simfile_path=r'C:\ProgramFiles(x86)\CarSim2022.1_Data\simfile.sim'self.vs=vs_solver.vs_solver()self.vs_dll_exist_flag=self.vs_dll_is_exist()self.configuration=self.vs.read_configuration(self.simfile_path)defvs_dll_is_exist(self):dll_path=self.vs.get_dll_path(self.simfile_path)ifdll_pathisnotNoneandos.path.exists(dll_path):vs_dll=ctypes.cdll.LoadLibrary(dll_path)ifself.vs.get_api(vs_dll):exist_flag=Trueelse:exist_flag=Falseprint(f'cannotgetdllapi,pleasecheckthedll{dll_path}')else:exist_flag=Falseprint(f'pleasecheckdll_pathorsimfile_pathexistenceornot')returnexist_flagdefget_export_array(self):returnself.vs.copy_export_vars(carsim_sim.configuration.get('n_export'))defget_time_step(self):returnself.configuration.get('t_step')defstop(self,t_current):self.vs.terminate_run(t_current)if__name__=='__main__':carsim_sim=carsim_simulation()t_current=carsim_sim.get_time_step()export_array=carsim_sim.get_export_array()status=0whilestatus==0:#更新当前时间t_current=t_current+carsim_sim.get_time_step()import_array=[0.1,0,0]3status,export_array=carsim_sim.vs.integrate_io(t_current,import_array,export_array)print(f'current_x:{export_array[0]},current_y:{export_array[6]}')ifkeyboard.is_pressed('q'):carsim_sim.stop(t_current)break12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849四、运行carsim1)运行carsim等待几秒会出现黑窗,然后关掉黑窗即可。五、运行python1)运行python脚本之后结果哗啦啦就出来了,就很简单。六、补充vs_solver.py代码#Copyright(c)2019-2020,MechanicalSimulationCorporation#Allrightsreserved.##THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSOR#IMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,#FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHE#AUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHER#LIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM,#OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN#THESOFTWARE.importctypesimportsys,string,os,reclassvs_solver:def__init__(self):self.dll_handle=Nonedefget_api(self,dll_handle):self.dll_handle=dll_handleifdll_handle.vs_runisnotNoneand\dll_handle.vs_initializeisnotNoneand\dll_handle.vs_read_configurationisnotNoneand\dll_handle.vs_integrate_ioisnotNoneand\dll_handle.vs_copy_export_varsisnotNoneand\dll_handle.vs_terminate_runisnotNoneand\dll_handle.vs_error_occurredisnotNoneand\dll_handle.vs_set_opt_error_dialogisnotNoneand\dll_handle.vs_get_error_messageisnotNoneand\dll_handle.vs_road_lisnotNone:dll_handle.vs_road_l.restype=ctypes.c_double#vsimports=(ctypes.c_double*1)()#vsexports=(ctypes.c_double*1)()#dll_handle.vs_integrate_io.argtypes=[ctypes.c_double,ctypes.byref(vsimports),ctypes.byref(vsexports)]##dll_handle.vs.integrate_io.argtypes=[ctypes.c_double,ctypes.c_int]returnTrueelse:returnFalsedefget_char_pointer(self,python_string):#pythonversionisgreaterorequalto3.0thenweneedtodefinetheencodingwhenconvertingastringto#bytes.Oncethatisdonewecanconvertthethepythonstringtoachar*.ifsys.version_info>=(3,0):char_pointer=ctypes.c_char_p(bytes(python_string,'UTF-8'))else:char_pointer=ctypes.c_char_p(bytes(python_string))returnchar_pointerdefget_parameter_value(self,line):index=line.find('')ifindex>=0:returnline[index:].strip()else:returnNonedefget_dll_path(self,path_to_sim_file):dll_path=Noneprog_dir=Noneveh_code=Noneproduct_name=Noneproduct_ver=Nonelibrary_name=Nonebitness_suffix='_64'ifctypes.sizeof(ctypes.c_voidp)==8else'_32'platform=sys.platformsim_file=open(path_to_sim_file,'r')if(platform=='linux'):libfiletype='SOFILE'else:libfiletype='DLLFILE'forlineinsim_file:ifline.lstrip().startswith('PROGDIR'):prog_dir=self.get_parameter_value(line)ifprog_dir=='.':prog_dir=os.getcwd()elifline.lstrip().startswith(libfiletype):dll_path=self.get_parameter_value(line)elifline.lstrip().startswith('VEHICLE_CODE'):veh_code=self.get_parameter_value(line)elifline.lstrip().startswith('PRODUCT_ID'):product_name=self.get_parameter_value(line)elifline.lstrip().startswith('PRODUCT_VER'):product_ver=self.get_parameter_value(line)sim_file.close()if"tire"inveh_code:ifplatform=='linux':library_name='libtire.so.%s'%(product_ver)else:library_name="tire"+bitness_suffixelifproduct_name=="CarSim":ifplatform=='linux':library_name='libcarsim.so.%s'%(product_ver)else:library_name="carsim"+bitness_suffixelifproduct_name=="TruckSim":ifplatform=='linux':library_name='libtrucksim.so.%s'%(product_ver)else:library_name="trucksim"+bitness_suffixelifproduct_name=="BikeSim":ifplatform=='linux':library_name='libbikesim.so.%s'%(product_ver)else:library_name="bikesim"+bitness_suffixelse:ifplatform=='linux':library_name='libcarsim.so.%s'%(product_ver)else:library_name=veh_code+bitness_suffixifdll_pathisNone:ifsys.platform=='linux':dll_path=os.path.join(prog_dir,library_name);else:dll_path=os.path.join(prog_dir,"Programs","Solvers",library_name+".dll")returndll_pathdefrun(self,path_to_sim_file):error_occurred=1path_to_sim_file_ptr=self.get_char_pointer(path_to_sim_file)ifpath_to_sim_file_ptrisnotNone:error_occurred=self.dll_handle.vs_run(path_to_sim_file_ptr)returnerror_occurreddefprint_error(self):error_string=ctypes.c_char_p(self.dll_handle.vs_get_error_message())print(error_string.value.decode('ascii'))defread_configuration(self,path_to_sim_file):path_to_sim_file_ptr=self.get_char_pointer(path_to_sim_file)platform=sys.platformifpath_to_sim_file_ptrisnotNone:ifplatform=='linux':ref_n_import=ctypes.c_long()ref_n_export=ctypes.c_longlong()else:ref_n_import=ctypes.c_int32()ref_n_export=ctypes.c_int64()ref_t_start=ctypes.c_double()ref_t_stop=ctypes.c_double()ref_t_step=ctypes.c_double()self.dll_handle.vs_read_configuration(path_to_sim_file_ptr,ctypes.byref(ref_n_import),ctypes.byref(ref_n_export),ctypes.byref(ref_t_start),ctypes.byref(ref_t_stop),ctypes.byref(ref_t_step))configuration={'n_import':ref_n_import.value,'n_export':ref_n_export.value,'t_start':ref_t_start.value,'t_stop':ref_t_stop.value,'t_step':ref_t_step.value}returnconfigurationdefcopy_export_vars(self,n_export):export_array=(ctypes.c_double*n_export)()self.dll_handle.vs_copy_export_vars(ctypes.cast(export_array,ctypes.POINTER(ctypes.c_double)))export_list=[export_array[i]foriinrange(n_export)]returnexport_listdefget_road_l(self,x,y):x_c_double=ctypes.c_double(x)y_c_double=ctypes.c_double(y)c_double_return=self.dll_handle.vs_road_l(x_c_double,y_c_double)returnfloat(c_double_return)defintegrate_io(self,t_current,import_array,export_array):t_current_c_double=ctypes.c_double(t_current)import_c_double_array=(ctypes.c_double*len(import_array))(*import_array)export_c_double_array=(ctypes.c_double*len(export_array))(*export_array)c_integer_return=self.dll_handle.vs_integrate_io(t_current_c_double,ctypes.byref(import_c_double_array),ctypes.byref(export_c_double_array))export_array=[export_c_double_array[i]foriinrange(len(export_array))]returnc_integer_return,export_arraydefinitialize(self,t):t_c_double=ctypes.c_double(t)self.dll_handle.vs_initialize(t_c_double)defterminate_run(self,t):t_c_double=ctypes.c_double(t)self.dll_handle.vs_terminate_run(t_c_double)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193总结1、这里关于solvers的细节其实都没说,因为里面确实也没什么内容好讲的,本质就是调用carsim.dll,如果你需要更多的函数解析其实可以看vs_api.h,路径在C:\ProgramFiles(x86)\CarSim2022.1_Data\Extensions\Custom_C\common,具体内容如下图所示。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 12:46 , Processed in 1.163677 second(s), 25 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表