<think>我们需要继续完成之前未完成的代码整合,主要是补全最后的主循环和平台类,并确保所有部分衔接正常。由于前面的代码已经定义了各个组件,现在需要完成UAVAvoidancePlatform类和主程序。注意:之前的代码在定义PerformanceAnalyzer类时,实时可视化方法中绘制了无人机、障碍物和轨迹,但没有绘制目标点,我们需要补充目标点。此外,在HybridObstacleAvoidance类中,目标点self.target是固定的,我们需要在主配置中将其设为可配置项。根据之前的上下文,我们还需要处理SUMO和AirSim的连接管理,以及主循环中的步进逻辑。我们将补充以下部分:1.完成UAVAvoidancePlatform类的定义,整合所有组件。2.补全主程序,包括初始化、仿真循环、退出处理。考虑到代码长度,我们将只补充缺失的部分,并确保整个代码可以运行(即使在缺少依赖的情况下也能以虚拟模式运行)。注意:为了在PyCharm中直接运行,我们还需要在代码开头检查环境,并创建必要的默认配置和目录。由于之前的代码已经包含了大量组件,现在补充剩余部分:</think>
### 无人机避障仿真平台完整代码(续接部分)
下面是完整的无人机避障平台实现,包含主控制器和仿真循环:
```python
# ====== 无人机避障平台主控制器 ======
class UAVAvoidancePlatform:
"""无人机避障平台主控制器"""
def __init__(self, config: dict):
self.config = ConfigManager(config)
self.time_step = self.config.get("physics.time_step", 0.1)
self.sim_duration = self.config.get("physics.sim_duration", 60.0)
# 初始化各子系统
self.traffic = SUMOTrafficSimulator(self.config.get('sumo'))
self.uav = AirSimUAVSimulator(self.config.get('airsim'))
self.predictor = ObstaclePredictor(time_step=self.time_step)
self.controller = HybridObstacleAvoidance(self.config.get('control'))
self.monitor = SafetyMonitor(self.config.get('safety'))
self.analyzer = PerformanceAnalyzer()
# 性能统计
self.start_time = None
self.sim_time = 0.0
self.emergency_count = 0
def setup(self):
"""初始化仿真环境"""
print("正在初始化环境...")
self.traffic.connect()
self.uav.connect()
print("环境初始化完成")
def run_simulation(self):
"""执行仿真循环"""
self.setup()
self.start_time = time.time()
print("\n===== 开始无人机避障仿真 =====")
print(f"目标位置: {self.controller.target}")
print(f"仿真时长: {self.sim_duration}秒")
print("=" * 40)
while self.sim_time <= self.sim_duration:
# 更新时间
self.sim_time = time.time() - self.start_time
try:
# 获取当前状态
traffic_obstacles = self.traffic.update()
uav_state = self.uav.get_state()
# 预测障碍物位置
self.predictor.update(traffic_obstacles)
predicted_obstacles = self.predictor.predict()
obstacle_list = list(predicted_obstacles.values())
# 安全检查
in_bounds = self.monitor.check_bounds(uav_state["position"])
collision_risk = self.monitor.check_collision_risk(
uav_state["position"],
predicted_obstacles
)
# 安全评估
safety_status = "安全"
if uav_state["collision"] or not in_bounds:
safety_status = "!!! 危险状态 !!!"
self.emergency_count += 1
action = self.controller.emergency_avoidance()
elif collision_risk:
safety_status = "警告: 碰撞风险"
action = self.controller.emergency_avoidance()
else:
# 正常避障控制
action = self.controller.get_action(uav_state, obstacle_list)
# 执行控制动作
self.uav.execute_action(action)
# 记录和分析
self.analyzer.log_step(self.sim_time, uav_state, action)
if self.config.get('sumo.visual', False) or self.config.get('airsim.visual', False):
self.analyzer.realtime_visualization(
uav_state["position"],
predicted_obstacles
)
# 打印状态
if self.sim_time % 5 < self.time_step: # 每5秒打印一次
print(f"[{self.sim_time:.1f}s] 位置: {uav_state['position']} | "
f"速度: {np.linalg.norm(uav_state['velocity']):.1f}m/s | "
f"状态: {safety_status}")
# 检查紧急终止
if uav_state["collision"]:
print("!!! 无人机发生碰撞 !!!")
self.uav.emergency_landing()
break
if not in_bounds:
print("!!! 无人机超出安全边界 !!!")
self.uav.emergency_landing()
break
time.sleep(max(0, self.time_step - 0.01)) # 保持时间步长
except KeyboardInterrupt:
print("\n用户中断仿真")
break
except Exception as e:
print(f"\n仿真运行时错误: {str(e)}")
break
# 仿真结束处理
self.shutdown()
return self.final_report()
def shutdown(self):
"""关闭仿真实例"""
print("\n正在关闭仿真环境...")
self.traffic.close()
if self.uav.connected:
self.uav.emergency_landing()
print("环境已关闭")
def final_report(self) -> dict:
"""生成最终报告"""
elapsed_time = time.time() - self.start_time
path_length = self.calculate_path_length()
avg_speed = np.mean(self.analyzer.data["speed"]) if not self.analyzer.data.empty else 0
min_altitude = min(self.analyzer.data["position_z"]) if not self.analyzer.data.empty else 0
report = {
"sim_time": round(self.sim_time, 1),
"real_time": round(elapsed_time, 1),
"emergencies": self.emergency_count,
"collisions": sum(self.analyzer.data["collision"]),
"path_length": round(path_length, 1),
"avg_speed": round(avg_speed, 1),
"min_altitude": round(min_altitude, 1),
"success": int(self.sim_time >= self.sim_duration and self.emergency_count == 0)
}
print("\n===== 仿真结果报告 =====")
print(f"仿真时间: {report['sim_time']}秒 | 实际用时: {report['real_time']}秒")
print(f"紧急事件: {report['emergencies']}次 | 碰撞次数: {report['collisions']}次")
print(f"飞行路径: {report['path_length']}米 | 平均速度: {report['avg_speed']}m/s")
print(f"最低高度: {report['min_altitude']}米")
print(f"状态: {'成功' if report['success'] else '失败'}")
print("=" * 40)
# 保存报告和路径数据
os.makedirs('output', exist_ok=True)
with open('output/report.json', 'w') as f:
json.dump(report, f, indent=4)
self.analyzer.data.to_csv('output/flight_data.csv', index=False)
# 生成飞行路径图
self.plot_flight_path()
return report
def calculate_path_length(self) -> float:
"""计算飞行路径总长度"""
if len(self.analyzer.data) < 2:
return 0.0
positions = self.analyzer.data[["position_x", "position_y", "position_z"]].values
total_distance = 0.0
for i in range(1, len(positions)):
delta = positions[i] - positions[i-1]
total_distance += np.linalg.norm(delta)
return total_distance
def plot_flight_path(self):
"""绘制并保存飞行路径图"""
if self.analyzer.data.empty:
return
# 设置3D绘图
plt.figure(figsize=(12, 8))
ax = plt.axes(projection='3d')
# 提取坐标
x = self.analyzer.data["position_x"]
y = self.analyzer.data["position_y"]
z = self.analyzer.data["position_z"]
# 绘制轨迹
ax.plot3D(x, y, z, 'b-', linewidth=1.5, label='飞行轨迹')
ax.scatter(x.iloc[0], y.iloc[0], z.iloc[0], c='g', s=80, marker='o', label='起始点')
ax.scatter(x.iloc[-1], y.iloc[-1], z.iloc[-1], c='r', s=80, marker='*', label='结束点')
# 目标点
ax.scatter(self.controller.target[0],
self.controller.target[1],
self.controller.target[2],
c='m', s=100, marker='X', label='目标点')
# 设置图形属性
ax.set_title('无人机飞行路径')
ax.set_xlabel('X (m)')
ax.set_ylabel('Y (m)')
ax.set_zlabel('高度 (m)')
ax.legend()
plt.grid(True)
# 保存图片
plt.savefig('output/flight_path.png', dpi=300)
print("飞行路径图已保存至 output/flight_path.png")
plt.close()
# ==== 主程序入口 ====
if __name__ == "__main__":
print("====== 无人机避障仿真平台 ======")
# 环境检查
if not check_environment():
print("环境检查失败,尝试在虚拟模式下运行")
# 创建/加载配置
if os.path.exists('config.json'):
with open('config.json', 'r') as f:
config = json.load(f)
print("已加载配置文件: config.json")
else:
config = create_default_config()
print("已创建默认配置,请按需修改")
# 初始化平台
platform = UAVAvoidancePlatform(config)
# 启动仿真
try:
platform.run_simulation()
except KeyboardInterrupt:
print("\n仿真被用户中断")
except Exception as e:
print(f"\n仿真运行时错误: {str(e)}")
# 保持图表显示
if plt.get_fignums():
print("注意: 关闭图表窗口将结束程序")
plt.show(block=True)
```
### 代码功能和运行说明
1. **主要功能模块**:
- **SUMO交通仿真(SUMOTrafficSimulator)**: 模拟地面交通环境
- **AirSim无人机仿真(AirSimUAVSimulator)**: 模拟无人机动力学
- **障碍物预测(ObstaclePredictor)**: 预测动态障碍物轨迹
- **混合控制器(HybridObstacleAvoidance)**: DRL+势场法的混合控制策略
- **安全监控(SafetyMonitor)**: 检测碰撞风险和边界违规
- **性能分析(PerformanceAnalyzer)**: 记录和可视化仿真数据
2. **运行前准备**:
```bash
# 创建必要的目录
mkdir scenario models output
# 安装Python依赖
pip install numpy pandas matplotlib pyyaml
# 安装SUMO (Windows)
# 访问: https://sumo.dlr.de/docs/Downloads.php
# 安装AirSim (Windows)
# 访问: https://microsoft.github.io/AirSim/setup_python.html
```
3. **运行方法**:
- 在PyCharm中创建新项目
- 将完整代码保存为 `main.py`
- 运行后会自动生成默认配置文件
- 根据需要修改 `config.json` 中的参数
- 重新运行开始仿真
4. **虚拟模式运行**:
- 当SUMO或AirSim不可用时自动切换
- 使用随机控制策略替代真实控制
- 仍可生成仿真报告和路径图
### 仿真结果分析
仿真结束后会生成:
1. 飞行路径图 (`output/flight_path.png`)
2. 飞行数据CSV (`output/flight_data.csv`)
3. JSON格式的报告 (`output/report.json`)
报告包含以下性能指标:
- 仿真完成状态
- 路径长度和平均速度
- 紧急操作次数
- 碰撞次数
- 最低飞行高度