How to load Dymola simulation results into Python?

73 Views Asked by At

I want to read the result of my Dymola simulation into python to plot some variables. After the simulation I have the data as Matlab .mat file Do i have the option to export the results into the SDF format?

My first try to read the data into python doesn't work really well.

import scipy.io

# Pfad zur MAT-Datei definieren
dateipfad = r'C:\Users\Benutzername\Desktop\Python Interface for Dymola_test\HeatPumpCycle_CO2_0.30.mat'

# MAT-Datei einlesen
mat_contents = scipy.io.loadmat(dateipfad)

# Namen und Werte aller Variablen in der MAT-Datei ausgeben
for variable_name in mat_contents.keys():
    variable_value = mat_contents[variable_name]
    print(f"Variable '{variable_name}':")
    print(variable_value)
    print()

enter image description here

2

There are 2 best solutions below

2
marco On

The problem with your .mat file is, that Dymola uses a very specific format to store its data to reduce the file size. In a typical Modelica model you have lots of alias-variables, e.g. caused by connecting multiple components which all have the same potential at the connection point. To reduce the file size, the time series for the potentials is only stored once and multiple variables link to it. Therefore you need to unwrap that data and check which variable links to which time series.

The SDF python package can do that:

import sdf
file = r'C:\tmp\sim_result.mat'
data = sdf.load(file)

# print name and final value of all trajectories in .mat file
for ds in data.datasets:
    print(ds.name)
    print(ds.data[-1])

You could also convert the mat file to sdf first (using dsres2sdf.exe, found in the Dymola installation folder), but as you see above this is not necessary.

If SDF does not fit your needs, there is also DyMat.

You can also retrieve the data via the dymola python interface using readTrajectory, but that's the slowest solution and needs a running dymola instance.

0
Dag B On

The easiest was is to open Simulation>Setup>Output, and the under post-processing commands you tick the alternative that converts the result file to SDF. Then you get an SDF file every time you run a simulation.