简体   繁体   English

如何使用 python 将变量从 .mat 文件(由 Dymola 生成)导出到 .csv

[英]How can I export variables from .mat file (generated by Dymola) to .csv using python

I'm a student who is quite new to coding in Python.我是一名学生,对 Python 中的编码非常陌生。 I'm using Dymola for several years and now I'm using the Dymola/Python interface with which you can operate Dymola from inside Python (useful for building stock simulations, global sensitivity analysis etc.).我使用 Dymola 已经好几年了,现在我正在使用 Dymola/Python 界面,您可以使用它从 Python 内部操作 Dymola(用于构建股票模拟、全局敏感性分析等)。

Now, Dymola always generates.mat files in an efficient unreadable data structure.现在,Dymola 始终以高效的不可读数据结构生成 .mat 文件。 I was wondering how to export variables I'm interested in from that.mat-file to.csv using a Python-script?我想知道如何使用 Python 脚本将我感兴趣的变量从 that.mat 文件导出到.csv? (I don't want the whole file to be converted to.csv because it is simple way too large) (我不希望将整个文件转换为.csv,因为它太简单了)

I'm aware of a DyMat-package for Python that should do the job but either I don't understand the code or the code is not doing what it should do?我知道 Python 的 DyMat 包应该可以完成这项工作,但要么我不理解代码,要么代码没有做它应该做的事情? Does anybody have experience with this?有人有这方面的经验吗? I probably miss some code defining which.mat file has to be read/exported from, which variables I want and in which directory the result.csv-file should be stored?我可能错过了一些定义必须从哪个.mat 文件读取/导出的代码,我想要哪些变量以及 result.csv 文件应该存储在哪个目录中?

import csv, numpy

def export(dm, varList, fileName=None, formatOptions={}):
    """Export DyMat data to a CSV file"""

    if not fileName:
        fileName = dm.fileName + '.csv'
    oFile = open(fileName, 'w')
    csvWriter = csv.writer(oFile)

    vDict = dm.sortByBlocks(varList)
    for vList in vDict.values():
        vData = dm.getVarArray(vList)
        vList.insert(0, dm._absc[0])
        csvWriter.writerow(vList)
        csvWriter.writerows(numpy.transpose(vData))

    oFile.close()

Thanks!谢谢!

Since this was tagged openmodelica , I am proposing a solution using it:由于这被标记为openmodelica ,我提出了一个使用它的解决方案:

filterSimulationResults ("file.mat", "file.csv", {"x","y","z"}) creates a csv-file with only variables x, y, z (If you think it's still too large, it is possible to resample the file). filterSimulationResults ("file.mat", "file.csv", {"x","y","z"}) 创建一个仅包含变量 x、y、z 的 csv 文件(如果您认为它仍然太大,可以重新采样文件)。

In the Dymola distribution there is a utility called alist.exe, that allows you to export a number of variables in CSV format.在 Dymola 发行版中有一个名为 alist.exe 的实用程序,它允许您以 CSV 格式导出许多变量。

Another possibility is to convert the MAT file to SDF format, which is a very simple HDF5 interpretation.另一种可能是将 MAT 文件转换为 SDF 格式,这是一种非常简单的 HDF5 解释。 The HDF5 file is not as compact as the MAT-file, but you can compress the file using ZIP/GZIP/7ZIP to reduce archival storage. HDF5 文件不像 MAT 文件那样紧凑,但您可以使用 ZIP/GZIP/7ZIP 压缩文件以减少存档存储。 There are both MATLAB and Python scripts for reading the SDF format in the Dymola distribution.在 Dymola 发行版中,有 MATLAB 和 Python 脚本用于读取 SDF 格式。

For small files (<2GB) Buildingspy (or other Python packages) covers pretty much all needs: https://simulationresearch.lbl.gov/modelica/buildingspy/对于小文件 (<2GB) Buildingspy(或其他 Python 软件包)几乎涵盖了所有需求: https://simulationresearch.lbl.gov/modelica/buildingspy/

However, since one will run into issues when the files are above 2GB (eg for full years of simulations), "alist.exe" from Dymola may be employed.然而,当文件超过 2GB 时会遇到问题(例如,对于整年的模拟),可以使用来自 Dymola 的“alist.exe”。 (filterSimulationResults from OpenModelica also fails then) (来自 OpenModelica 的 filterSimulationResults 也会失败)

"alist.exe" seems to accept up until approx. “alist.exe”似乎可以接受直到大约。 100 variables to be exported at once and single executions for each variable seems to slow things down drastically (translation of 1 or 100 rows takes almost the same time).一次导出 100 个变量并且每个变量的单次执行似乎会大大减慢速度(翻译 1 行或 100 行几乎需要相同的时间)。 One may employ the alist.exe as follows from Python to facilitate automation and speed things up.可以使用 Python 中的 alist.exe 来促进自动化并加快速度。

var_list=['Component.Name1','Component.Name3','Component.Name2','...'] #List of Variabels to be extracted
N_batch=100 #Number of variables to be extracted from the .mat file at once (max. approx 110)

cmds=[]        #list of commands to be executed batch wise 

for i,var in enumerate(var_list):
    if (i%N_batch == 0) &(i > 0):
        cmds.append(cmd)
        cmd=''
    cmd+=f' -e {var}'#build command
    
cmds.append(cmd)


lst_df=[]       #list of pandas dataframes 
for i,cmd in enumerate(cmds):
    os.system(f'"C:/Program Files/Dymola 2021/bin64/alist.exe" {cmd} {inFile} tmp.csv')
    lst_df.append(pd.read_csv('tmp.csv',index_col=[0]).squeeze("columns"))

df_overall=pd.concat(lst_df,axis=1)
df_overall.to_csv('CompleteCSVFile.csv')#or use .pkl for more efficient writing and reading

Hope this helps someone someday!希望有一天这对某人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 将复杂的 .mat 文件转换为 csv - How can I convert complex .mat file to csv using python Export.csv 文件 from.mat 使用 OpenModelica 生成的文件 - Export .csv file from .mat file generated with OpenModelica 如何将数据从 Python 导出到 a.csv 文件? - How can I export data from Python to a .csv file? 如何将所有变量从项目导出到.csv,以便随后将其导入Python环境? - How do I export all variables from a project to .csv so that I can then import them into a Python environment? 如何让 python 将我抓取的变量导出为 a.csv? - How can I have python export my scraped variables as a .csv? 如何使用 python 将.mat 文件转换为 csv? - How to convert .mat file into csv using python? 如何在python生成的CSV文件中添加编码 - How can i add encoding to the python generated CSV file 如何使用 python 将 html 表导出到 csv 文件? - How do I export html table to csv file using python? 如何从 python 导出 .csv 文件并使用 pandas DataFrame - How to export .csv file from python and using pandas DataFrame 如何从CSV文件中提取数据列并将其定义为x和y变量,然后使用pylab在python中绘制它们? - How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM