From e2f387ec172577d0e9491202841e04de97076070 Mon Sep 17 00:00:00 2001 From: 22268 <2226804607@qq.com> Date: Sat, 20 Dec 2025 02:30:51 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=97=A0=E4=BA=BA=E8=BD=A6=E6=B8=A9?= =?UTF-8?q?=E5=BA=A6=E7=9B=91=E6=8E=A7=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/minicarsim/main.py | 221 ++++++++++++++++++++++++++- src/minicarsim/models/simple_car.xml | 2 + 2 files changed, 220 insertions(+), 3 deletions(-) diff --git a/src/minicarsim/main.py b/src/minicarsim/main.py index 73ab5d5ff6..bf8e649ef8 100644 --- a/src/minicarsim/main.py +++ b/src/minicarsim/main.py @@ -29,6 +29,13 @@ # 仿真帧数 SIMULATION_FRAMES = 1000 +# 温度监测参数 +TEMPERATURE_PARAMS = { + "ambient_temp": 25.0, # 环境基础温度 (摄氏度) + "temp_variation": 5.0, # 温度变化幅度 + "heat_sources": ["obstacle1", "obstacle2", "obstacle3", "obstacle4", "obstacle5"] # 热源物体 +} + # ------------------------------------------------------------- @@ -390,6 +397,199 @@ def _plot_bounding_box(self, ax, corners, color): [corners[i, 2], corners[i + 4, 2]], c=color, alpha=0.7) + def simulate_temperature_data(self): + """ + 模拟温度数据采集 + 基于车辆位置和热源位置计算温度 + """ + try: + # 获取车辆位置 + vehicle_pos, _ = self.get_world_pose("vehicle") + lidar_site_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_SITE, "lidar_site") + if lidar_site_id >= 0: + sensor_pos = self.data.site_xpos[lidar_site_id].copy() + else: + sensor_pos = vehicle_pos + np.array(LIDAR_PARAMS["pos"]) + except ValueError: + sensor_pos = np.array([0, 0, 0.8]) + + # 基础环境温度 + temperature = TEMPERATURE_PARAMS["ambient_temp"] + + # 遍历热源物体,计算对温度的影响 + for heat_source in TEMPERATURE_PARAMS["heat_sources"]: + try: + # 获取热源位置 + body_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, heat_source) + heat_pos = self.data.xpos[body_id].copy() + + # 计算传感器与热源的距离 + distance = np.linalg.norm(sensor_pos - heat_pos) + + # 根据距离计算温度影响(假设热源散发热量遵循平方反比定律) + # 距离越近,温度越高 + temp_increase = TEMPERATURE_PARAMS["temp_variation"] / (distance + 1) # 避免除零 + temperature += temp_increase + + except Exception: + # 如果找不到热源,跳过 + continue + + # 添加随机噪声模拟真实传感器 + noise = np.random.normal(0, 0.5) # 均值为0,标准差为0.5的高斯噪声 + temperature += noise + + return temperature + + def visualize_temperature_data(self, temperature, detected_objects): + """ + 生成温度分布可视化图 + """ + fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 7)) + + # 左侧图:温度随时间变化趋势 + # 由于我们是单帧数据,这里展示当前温度信息 + ax1.set_xlim(0, 10) + ax1.set_ylim(TEMPERATURE_PARAMS["ambient_temp"] - 5, + TEMPERATURE_PARAMS["ambient_temp"] + TEMPERATURE_PARAMS["temp_variation"] + 5) + ax1.axhline(y=TEMPERATURE_PARAMS["ambient_temp"], color='b', linestyle='--', + label=f'环境温度: {TEMPERATURE_PARAMS["ambient_temp"]:.1f}°C') + ax1.bar([5], [temperature], width=2, color='r', alpha=0.7, + label=f'测量温度: {temperature:.1f}°C') + ax1.set_xlabel('时间') + ax1.set_ylabel('温度 (°C)') + ax1.set_title(f'温度监测 - 帧 {self.frame_count:04d}') + ax1.legend() + ax1.grid(True) + + # 右侧图:温度与物体距离关系 + if detected_objects: + distances = [obj['distance'] for obj in detected_objects] + object_names = [obj['name'] for obj in detected_objects] + + # 计算每个物体附近的预期温度 + expected_temps = [] + try: + sensor_pos = self.data.site_xpos[ + mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_SITE, "lidar_site") + ].copy() + + for obj in detected_objects: + obj_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, obj['name']) + obj_pos = self.data.xpos[obj_id].copy() + distance = np.linalg.norm(sensor_pos - obj_pos) + expected_temp = TEMPERATURE_PARAMS["ambient_temp"] + \ + TEMPERATURE_PARAMS["temp_variation"] / (distance + 1) + expected_temps.append(expected_temp) + except: + # 如果出错,使用简化计算 + expected_temps = [TEMPERATURE_PARAMS["ambient_temp"] + + TEMPERATURE_PARAMS["temp_variation"] / (d + 1) for d in distances] + + x_pos = range(len(distances)) + ax2.bar(x_pos, expected_temps, alpha=0.7, color='orange', label='预期温度') + ax2.axhline(y=temperature, color='r', linestyle='-', label=f'实测温度: {temperature:.1f}°C') + + ax2.set_xlabel('物体') + ax2.set_ylabel('温度 (°C)') + ax2.set_title('物体距离与温度关系') + ax2.set_xticks(x_pos) + ax2.set_xticklabels([name[-1] for name in object_names]) # 只显示编号 + ax2.legend() + ax2.grid(True) + else: + ax2.text(0.5, 0.5, '无检测到物体', horizontalalignment='center', + verticalalignment='center', transform=ax2.transAxes) + ax2.set_title('物体距离与温度关系') + + plt.tight_layout() + plt.savefig(f"{self.output_dir}/visualization/temp_frame_{self.frame_count:04d}.png", + dpi=300, bbox_inches='tight') + plt.close() + + print(f"已生成温度可视化图: temp_frame_{self.frame_count:04d}.png") + + def generate_thermal_map(self, temperature, detected_objects): + """ + 生成热力图(二维温度分布图) + """ + fig, ax = plt.subplots(figsize=(10, 8)) + + # 创建网格点用于绘制热力图 + grid_size = 50 + x_range = np.linspace(-10, 15, grid_size) + y_range = np.linspace(-8, 8, grid_size) + X, Y = np.meshgrid(x_range, y_range) + + # 计算每个网格点的温度值 + Z = np.zeros_like(X) + sensor_height = 0.8 # 传感器高度 + + for i in range(grid_size): + for j in range(grid_size): + # 当前网格点位置 + point_pos = np.array([X[j, i], Y[j, i], sensor_height]) + + # 基础环境温度 + temp = TEMPERATURE_PARAMS["ambient_temp"] + + # 遍历热源计算温度贡献 + for heat_source in TEMPERATURE_PARAMS["heat_sources"]: + try: + body_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, heat_source) + heat_pos = self.data.xpos[body_id].copy() + distance = np.linalg.norm(point_pos - heat_pos) + temp_increase = TEMPERATURE_PARAMS["temp_variation"] / (distance + 1) + temp += temp_increase + except: + continue + + Z[j, i] = temp + + # 绘制热力图 + im = ax.contourf(X, Y, Z, levels=50, cmap='hot') + plt.colorbar(im, ax=ax, label='温度 (°C)') + + # 绘制车辆位置 + try: + vehicle_pos, _ = self.get_world_pose("vehicle") + ax.plot(vehicle_pos[0], vehicle_pos[1], 'bo', markersize=10, label='车辆') + except: + pass + + # 绘制障碍物位置 + colors = ['red', 'green', 'blue', 'yellow', 'purple'] + for i, obstacle in enumerate(TEMPERATURE_PARAMS["heat_sources"]): + try: + body_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_BODY, obstacle) + pos = self.data.xpos[body_id].copy() + ax.plot(pos[0], pos[1], 's', color=colors[i % len(colors)], + markersize=8, label=obstacle) + except: + continue + + # 绘制温度传感器测量值 + try: + lidar_site_id = mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_SITE, "lidar_site") + if lidar_site_id >= 0: + sensor_pos = self.data.site_xpos[lidar_site_id].copy() + ax.plot(sensor_pos[0], sensor_pos[1], 'wo', markersize=6, + markeredgecolor='black', label=f'传感器({temperature:.1f}°C)') + except: + pass + + ax.set_xlabel('X (m)') + ax.set_ylabel('Y (m)') + ax.set_title(f'环境温度分布图 - 帧 {self.frame_count:04d}') + ax.legend() + ax.grid(True) + + plt.savefig(f"{self.output_dir}/visualization/thermal_map_{self.frame_count:04d}.png", + dpi=300, bbox_inches='tight') + plt.close() + + print(f"已生成温度分布热力图: thermal_map_{self.frame_count:04d}.png") + def run_simulation(self): """运行MuJoCo仿真并生成数据""" print("开始仿真...") @@ -413,6 +613,9 @@ def run_simulation(self): # 生成传感器数据和标注 lidar_data = self.generate_realistic_lidar_data() annotations = self.generate_annotations() + + # 新增:模拟温度数据 + temperature = self.simulate_temperature_data() # 基于传感器数据计算控制指令 left_speed, right_speed, steering_angle = self.calculate_avoidance_control( @@ -437,9 +640,21 @@ def run_simulation(self): # 生成识别效果图 self.visualize_detection(lidar_data, annotations) - - # 生成距离和方位分析图 - self.visualize_distance_analysis(annotations) + + # 新增:生成温度可视化图 + self.visualize_temperature_data(temperature, annotations["objects"]) + + # 新增:生成温度分布热力图 + self.generate_thermal_map(temperature, annotations["objects"]) + + # 在保存数据时也保存温度信息 + temp_data = { + "frame": self.frame_count, + "temperature": temperature, + "unit": "celsius" + } + with open(f"{self.output_dir}/annotations/temp_frame_{self.frame_count:04d}.json", "w") as f: + json.dump(temp_data, f, indent=4) print(f"已仿真 {i}/{SIMULATION_FRAMES} 帧") else: diff --git a/src/minicarsim/models/simple_car.xml b/src/minicarsim/models/simple_car.xml index cb6aa99be0..25e52b5c18 100644 --- a/src/minicarsim/models/simple_car.xml +++ b/src/minicarsim/models/simple_car.xml @@ -98,5 +98,7 @@ + + \ No newline at end of file From 35878fa0f27f44f95c42b2cd381cb8f1e4b96b4a Mon Sep 17 00:00:00 2001 From: 22268 <2226804607@qq.com> Date: Sat, 20 Dec 2025 20:01:04 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=97=A0=E4=BA=BA?= =?UTF-8?q?=E8=BD=A6=E6=B8=A9=E5=BA=A6=E8=87=AA=E5=8A=A8=E8=B0=83=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/minicarsim/README.md | 23 +++- src/minicarsim/main.py | 266 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 285 insertions(+), 4 deletions(-) diff --git a/src/minicarsim/README.md b/src/minicarsim/README.md index e709b4944b..71e8269a02 100644 --- a/src/minicarsim/README.md +++ b/src/minicarsim/README.md @@ -11,6 +11,9 @@ 3. **传感器模拟**:LiDAR传感器点云数据生成 4. **物体检测**:检测环境中的障碍物 5. **数据保存**:保存点云数据和检测结果 +6. **温度监控**:模拟车内温度变化并可视化 +7. **智能空调系统**:根据温度自动开启/关闭空调调节温度 +8. **温度调节可视化**:生成多种温度调节相关图表 ## 环境要求 @@ -29,6 +32,11 @@ minicarsim/ └── output/ # 输出数据目录 ├── lidar/ # LiDAR点云数据 └── annotations/ # 物体检测标注 + └── visualization/ # 可视化图表 + ├── temperature_trend.png # 温度变化趋势图 + ├── temperature_summary.png # 温度调节汇总图 + ├── ac_control_XXXX.png # 空调控制状态图 + └── thermal_map_XXXX.png # 环境温度分布图 ``` ## 快速开始 @@ -53,13 +61,19 @@ python main.py - `MojocoDataSim`: 主要的仿真类 - `generate_realistic_lidar_data()`: 生成真实的LiDAR点云数据 - `detect_objects()`: 检测环境中的物体 + - `simulate_temperature_data()`: 模拟车内温度变化 + - `check_and_control_ac()`: 检查并控制空调开关 - `run_simulation()`: 运行仿真主循环 + - `visualize_ac_control()`: 生成空调控制状态图 + - `generate_temperature_trend()`: 生成温度变化趋势图 + - `generate_temperature_summary_chart()`: 生成温度调节汇总图 ### 配置参数 在`main.py`中可以调整的主要参数: - `LIDAR_PARAMS`: LiDAR传感器参数 +- `TEMPERATURE_PARAMS`: 温度监控参数 - `SIMULATION_FRAMES`: 仿真总帧数 ## 模型说明 @@ -74,10 +88,15 @@ python main.py ## 数据输出 -仿真运行后会产生两类数据: +仿真运行后会产生三类数据: 1. **LiDAR点云数据**:保存为`.npy`格式的NumPy数组 2. **物体检测标注**:保存为`.json`格式的标注文件 +3. **温度调节可视化图表**: + - 温度变化趋势图 (`temperature_trend.png`) + - 温度调节汇总图 (`temperature_summary.png`) + - 空调控制状态图 (`ac_control_XXXX.png`) + - 环境温度分布图 (`thermal_map_XXXX.png`) ## 扩展建议 @@ -86,6 +105,7 @@ python main.py 3. 添加不同的环境地图 4. 实现自主导航功能 5. 添加更多的车辆控制方式 +6. 增强空调控制算法(PID控制等) ## 故障排除 @@ -94,6 +114,7 @@ python main.py 1. **找不到模型文件**:检查`XML_PATH`是否正确 2. **无法显示可视化窗口**:确保已正确安装MuJoCo 3. **没有检测到物体**:检查小车与物体之间的距离 +4. **温度调节效果不明显**:检查空调功率系数和舒适温度范围设置 ### 支持 diff --git a/src/minicarsim/main.py b/src/minicarsim/main.py index bf8e649ef8..ac7f7aeeaf 100644 --- a/src/minicarsim/main.py +++ b/src/minicarsim/main.py @@ -33,7 +33,9 @@ TEMPERATURE_PARAMS = { "ambient_temp": 25.0, # 环境基础温度 (摄氏度) "temp_variation": 5.0, # 温度变化幅度 - "heat_sources": ["obstacle1", "obstacle2", "obstacle3", "obstacle4", "obstacle5"] # 热源物体 + "heat_sources": ["obstacle1", "obstacle2", "obstacle3", "obstacle4", "obstacle5"], # 热源物体 + "comfort_range": [18.0, 28.0], # 舒适温度范围 (摄氏度) + "ac_power": 1.0 # 空调功率系数 } @@ -59,6 +61,12 @@ def __init__(self, xml_path, output_dir): print("仿真将在3秒后开始...") time.sleep(3) + # 初始化空调系统状态 + self.ac_status = False # 空调开关状态 + self.ac_target_temp = 23.0 # 空调目标温度 + self.comfort_min_temp = TEMPERATURE_PARAMS["comfort_range"][0] + self.comfort_max_temp = TEMPERATURE_PARAMS["comfort_range"][1] + def get_world_pose(self, body_name): """ 获取指定物体的世界位姿 @@ -439,6 +447,13 @@ def simulate_temperature_data(self): noise = np.random.normal(0, 0.5) # 均值为0,标准差为0.5的高斯噪声 temperature += noise + # 如果空调开启,调整温度 + if self.ac_status: + # 空调效果:逐渐向目标温度靠近 + temp_diff = self.ac_target_temp - temperature + ac_effect = temp_diff * TEMPERATURE_PARAMS["ac_power"] * 0.05 # 空调效果系数 + temperature += ac_effect + return temperature def visualize_temperature_data(self, temperature, detected_objects): @@ -590,6 +605,237 @@ def generate_thermal_map(self, temperature, detected_objects): print(f"已生成温度分布热力图: thermal_map_{self.frame_count:04d}.png") + def check_and_control_ac(self, temperature): + """ + 检查温度并控制空调开关 + :param temperature: 当前温度 + :return: 是否开启了空调 + """ + # 检查温度是否超出舒适范围 + if temperature < self.comfort_min_temp or temperature > self.comfort_max_temp: + # 如果温度不在舒适范围内,开启空调 + if not self.ac_status: + self.ac_status = True + print(f"🌡️ 空调已开启,当前温度: {temperature:.1f}°C,目标温度: {self.ac_target_temp:.1f}°C") + else: + # 如果温度在舒适范围内,关闭空调 + if self.ac_status: + self.ac_status = False + print(f"❄️ 空调已关闭,当前温度: {temperature:.1f}°C,处于舒适范围内") + + return self.ac_status + + def visualize_ac_control(self, temperature, ac_status): + """ + 生成空调控制状态可视化图 + :param temperature: 当前温度 + :param ac_status: 空调状态 + """ + fig, ax = plt.subplots(figsize=(10, 6)) + + # 绘制温度范围 + comfort_min = self.comfort_min_temp + comfort_max = self.comfort_max_temp + ambient_temp = TEMPERATURE_PARAMS["ambient_temp"] + + # 绘制舒适温度区域 + ax.axvspan(comfort_min, comfort_max, alpha=0.3, color='green', label='舒适温度区间') + + # 绘制环境温度线 + ax.axvline(ambient_temp, color='blue', linestyle='--', linewidth=1, label=f'环境温度 ({ambient_temp}°C)') + + # 绘制当前温度 + color = 'red' if ac_status else 'orange' + status_label = '空调运行中' if ac_status else '空调关闭' + ax.scatter(temperature, 1, s=100, color=color, label=f'当前温度 {temperature:.1f}°C ({status_label})') + + # 绘制目标温度(如果空调开启) + if ac_status: + ax.axvline(self.ac_target_temp, color='purple', linestyle='-.', linewidth=1, + label=f'目标温度 ({self.ac_target_temp}°C)') + + ax.set_xlim(ambient_temp - 10, ambient_temp + 10) + ax.set_ylim(0, 2) + ax.set_xlabel('温度 (°C)') + ax.set_title(f'空调控制系统状态 - 帧 {self.frame_count:04d}') + ax.legend() + ax.grid(True, alpha=0.3) + + # 移除y轴刻度 + ax.set_yticks([]) + + plt.tight_layout() + plt.savefig(f"{self.output_dir}/visualization/ac_control_{self.frame_count:04d}.png", + dpi=300, bbox_inches='tight') + plt.close() + + print(f"已生成空调控制状态图: ac_control_{self.frame_count:04d}.png") + + def generate_temperature_trend(self): + """ + 生成温度变化趋势图 + """ + # 读取之前保存的温度数据 + temp_files = [] + for file in os.listdir(f"{self.output_dir}/annotations"): + if file.startswith("temp_frame_") and file.endswith(".json"): + temp_files.append(file) + + if not temp_files: + return + + # 按帧排序 + temp_files.sort() + + frames = [] + temperatures = [] + ac_statuses = [] + + # 读取温度数据 + for file in temp_files: + with open(f"{self.output_dir}/annotations/{file}", "r") as f: + temp_data = json.load(f) + frames.append(temp_data["frame"]) + temperatures.append(temp_data["temperature"]) + ac_statuses.append(temp_data["ac_status"]) + + # 绘制温度变化趋势图 + fig, ax = plt.subplots(figsize=(12, 6)) + + # 绘制温度曲线 + ax.plot(frames, temperatures, 'o-', color='red', linewidth=2, markersize=4, label='实测温度') + + # 绘制舒适温度区间 + ax.axhspan(self.comfort_min_temp, self.comfort_max_temp, alpha=0.2, color='green', + label='舒适温度区间') + + # 绘制环境温度线 + ax.axhline(TEMPERATURE_PARAMS["ambient_temp"], color='blue', linestyle='--', + label=f'环境温度 ({TEMPERATURE_PARAMS["ambient_temp"]}°C)') + + # 标记空调开启的时间点 + ac_on_frames = [frames[i] for i in range(len(frames)) if ac_statuses[i]] + ac_on_temps = [temperatures[i] for i in range(len(temperatures)) if ac_statuses[i]] + if ac_on_frames: + ax.scatter(ac_on_frames, ac_on_temps, color='purple', s=50, marker='^', + label='空调运行中', zorder=5) + + ax.set_xlabel('帧序号') + ax.set_ylabel('温度 (°C)') + ax.set_title('温度变化趋势与空调控制状态') + ax.legend() + ax.grid(True, alpha=0.3) + + plt.tight_layout() + plt.savefig(f"{self.output_dir}/visualization/temperature_trend.png", dpi=300, bbox_inches='tight') + plt.close() + + print("已生成温度变化趋势图: temperature_trend.png") + + def generate_temperature_summary_chart(self): + """ + 生成温度调节汇总图,综合显示温度变化、空调状态和调节效果 + """ + # 读取之前保存的温度数据 + temp_files = [] + for file in os.listdir(f"{self.output_dir}/annotations"): + if file.startswith("temp_frame_") and file.endswith(".json"): + temp_files.append(file) + + if not temp_files: + return + + # 按帧排序 + temp_files.sort() + + frames = [] + temperatures = [] + ac_statuses = [] + target_temps = [] + + # 读取温度数据 + for file in temp_files: + with open(f"{self.output_dir}/annotations/{file}", "r") as f: + temp_data = json.load(f) + frames.append(temp_data["frame"]) + temperatures.append(temp_data["temperature"]) + ac_statuses.append(temp_data["ac_status"]) + target_temps.append(temp_data.get("ac_target_temp", None)) + + # 创建汇总图 + fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(15, 10)) + + # 第一个子图:温度变化和空调状态 + ax1.plot(frames, temperatures, 'o-', color='red', linewidth=2, markersize=4, label='实测温度') + ax1.axhspan(self.comfort_min_temp, self.comfort_max_temp, alpha=0.2, color='green', + label='舒适温度区间') + ax1.axhline(TEMPERATURE_PARAMS["ambient_temp"], color='blue', linestyle='--', + label=f'环境温度 ({TEMPERATURE_PARAMS["ambient_temp"]}°C)') + + # 标记空调开启的时间点 + ac_on_frames = [frames[i] for i in range(len(frames)) if ac_statuses[i]] + ac_on_temps = [temperatures[i] for i in range(len(temperatures)) if ac_statuses[i]] + if ac_on_frames: + ax1.scatter(ac_on_frames, ac_on_temps, color='purple', s=50, marker='^', + label='空调运行中', zorder=5) + + ax1.set_ylabel('温度 (°C)') + ax1.set_title('温度变化与空调控制状态') + ax1.legend() + ax1.grid(True, alpha=0.3) + + # 第二个子图:空调工作时的目标温度和调节效果 + # 只显示空调开启时的数据点 + ac_frames = [] + ac_temps = [] + ac_targets = [] + temp_differences = [] + + for i in range(len(frames)): + if ac_statuses[i] and target_temps[i] is not None: + ac_frames.append(frames[i]) + ac_temps.append(temperatures[i]) + ac_targets.append(target_temps[i]) + temp_differences.append(abs(temperatures[i] - target_temps[i])) + + if ac_frames: + ax2.plot(ac_frames, ac_temps, 'o-', color='red', linewidth=2, markersize=4, label='实测温度') + ax2.plot(ac_frames, ac_targets, 's-', color='purple', linewidth=2, markersize=4, label='目标温度') + + # 添加温度差值的柱状图 + ax3 = ax2.twinx() + bars = ax3.bar(ac_frames, temp_differences, alpha=0.3, color='orange', width=1.0, label='温度差值') + ax3.set_ylabel('温度差值 (°C)', color='orange') + ax3.tick_params(axis='y', labelcolor='orange') + + # 添加数值标签 + for bar, diff in zip(bars, temp_differences): + height = bar.get_height() + ax3.annotate(f'{diff:.1f}', + xy=(bar.get_x() + bar.get_width()/2, height), + xytext=(0, 3), # 3 points vertical offset + textcoords="offset points", + ha='center', va='bottom', fontsize=8, color='orange') + + ax2.set_xlabel('帧序号') + ax2.set_ylabel('温度 (°C)') + ax2.set_title('空调调节效果分析') + ax2.grid(True, alpha=0.3) + + # 合并图例 + if ac_frames: + lines2, labels2 = ax2.get_legend_handles_labels() + lines3, labels3 = ax3.get_legend_handles_labels() + ax2.legend(lines2 + lines3, labels2 + labels3, loc='upper left') + else: + ax2.legend() + + plt.tight_layout() + plt.savefig(f"{self.output_dir}/visualization/temperature_summary.png", dpi=300, bbox_inches='tight') + plt.close() + + print("已生成温度调节汇总图: temperature_summary.png") + def run_simulation(self): """运行MuJoCo仿真并生成数据""" print("开始仿真...") @@ -616,6 +862,9 @@ def run_simulation(self): # 新增:模拟温度数据 temperature = self.simulate_temperature_data() + + # 检查并控制空调 + ac_status = self.check_and_control_ac(temperature) # 基于传感器数据计算控制指令 left_speed, right_speed, steering_angle = self.calculate_avoidance_control( @@ -646,12 +895,17 @@ def run_simulation(self): # 新增:生成温度分布热力图 self.generate_thermal_map(temperature, annotations["objects"]) - + + # 新增:生成空调控制状态图 + self.visualize_ac_control(temperature, ac_status) + # 在保存数据时也保存温度信息 temp_data = { "frame": self.frame_count, "temperature": temperature, - "unit": "celsius" + "unit": "celsius", + "ac_status": ac_status, + "ac_target_temp": self.ac_target_temp if ac_status else None } with open(f"{self.output_dir}/annotations/temp_frame_{self.frame_count:04d}.json", "w") as f: json.dump(temp_data, f, indent=4) @@ -685,6 +939,12 @@ def run_simulation(self): # 控制仿真速度以便观察 time.sleep(0.01) + # 生成最终的温度趋势图 + self.generate_temperature_trend() + + # 生成温度调节汇总图 + self.generate_temperature_summary_chart() + print(f"仿真完成!数据已保存到:{self.output_dir}")