如何通过Python-Dymola接口实时查看Dymola模型仿真进度?
实时监控Dymola仿真进度与结果(Python接口)
针对你用Python调用高计算成本年度仿真模型的需求,以下是两种核心需求的解决方案:
一、实时查看仿真时间与预估耗时
默认simulateModel是阻塞调用,要实现实时监控需启用异步仿真模式,通过循环查询仿真状态获取进度:
from dymola.dymola_interface import DymolaInterface import time dymola = DymolaInterface() # 年度仿真总时长(示例:8760小时转换为秒) total_sim_time = 8760 * 3600 start_real_time = time.time() # 异步启动仿真,后台运行不阻塞Python脚本 simulation_task = dymola.simulateModel( "YourAnnualPerformanceModel", resultFile=r"N:\SOLAR\...\your_result_file", startTime=0, stopTime=total_sim_time, outputInterval=3600, # 每小时写入一次结果,平衡实时性与IO开销 asynchronous=True ) # 循环监控仿真进度 while dymola.isSimulationRunning(): current_sim_time = dymola.getSimulationTime() elapsed_real_time = time.time() - start_real_time # 计算进度与预估剩余时间 progress = (current_sim_time / total_sim_time) * 100 if progress > 0: estimated_total_real_time = elapsed_real_time / (progress / 100) remaining_real_time = estimated_total_real_time - elapsed_real_time print(f"进度: {progress:.2f}% | 当前仿真时间: {current_sim_time/3600:.2f}h | 已耗时: {elapsed_real_time/3600:.2f}h | 预估剩余: {remaining_real_time/3600:.2f}h") else: print(f"仿真初始化中... 当前仿真时间: {current_sim_time/3600:.2f}h") time.sleep(60) # 每分钟查询一次,可根据需求调整间隔 # 仿真结束后校验结果 if not simulation_task: print("仿真失败,日志如下:") print(dymola.getLastErrorLog()) dymola.close() exit(1) print("仿真完成") dymola.close()
二、实时查看仿真结果
可以通过两种方式读取仿真过程中已写入的变量数据:
方式1:通过Dymola官方接口读取
利用readSimulationResult函数直接读取结果文件中已保存的变量值,需与outputInterval配合设置读取频率:
# 在上述监控循环中加入以下代码 while dymola.isSimulationRunning(): current_sim_time = dymola.getSimulationTime() try: # 读取目标变量的最新值(示例:系统输出功率) power_value = dymola.readSimulationResult( r"N:\SOLAR\...\your_result_file", "System.OutputPower", current_sim_time ) print(f"[{current_sim_time/3600:.2f}h] 系统输出功率: {power_value:.2f} kW") except Exception as e: print(f"读取变量失败: {str(e)}") time.sleep(3600) # 与outputInterval同步,每小时读取一次
方式2:直接读取.mat结果文件
如果结果文件采用.mat格式,可借助scipy.io库实时读取已写入的部分数据:
from scipy.io import loadmat # 在监控循环中加入以下代码 while dymola.isSimulationRunning(): try: mat_data = loadmat(r"N:\SOLAR\...\your_result_file.mat") time_seq = mat_data['time'].flatten() power_seq = mat_data['System_OutputPower'].flatten() print(f"最新记录: [{time_seq[-1]/3600:.2f}h] 功率: {power_seq[-1]:.2f} kW") except Exception as e: print(f"读取.mat文件失败: {str(e)}") time.sleep(3600)
注意事项
outputInterval不要设置过小,否则会频繁写入磁盘,拖慢仿真速度- 异步仿真模式下,确保Python脚本不会提前退出,否则会终止Dymola仿真进程
- 超大模型的实时读取可能影响仿真性能,建议根据模型规模调整查询间隔
内容的提问来源于stack exchange,提问作者EngineerInProgress
相关产品推荐
相关产品推荐

