-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdsres.py
More file actions
173 lines (136 loc) · 4.6 KB
/
dsres.py
File metadata and controls
173 lines (136 loc) · 4.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from os import PathLike
import numpy as np
from sdf import Group, Dataset
import scipy.io
# extract strings from the matrix
def strMatNormal(a):
return ["".join(s).rstrip() for s in a]
def strMatTrans(a):
return ["".join(s).rstrip() for s in zip(*a)]
def _split_description(
comment: str,
) -> tuple[str | None, str | None, str | None, dict[str, str]]:
unit = None
display_unit = None
info = dict()
if comment.endswith("]"):
i = comment.rfind("[")
unit = comment[i + 1 : -1]
comment = comment[0:i].strip()
if unit is not None:
if ":#" in unit:
segments = unit.split(":#")
unit = segments[0]
for segment in segments[1:]:
key, value = segment[1:-1].split("=")
info[key] = value
if "|" in unit:
unit, display_unit = unit.split("|")
return unit, display_unit, comment, info
def load(filename: str | PathLike, objectname: str) -> Dataset | Group:
g_root = _load_mat(filename)
if objectname == "/":
return g_root
else:
obj = g_root
segments = objectname.split("/")
for s in segments:
if s:
obj = obj[s]
return obj
def _load_mat(filename: str) -> Group:
mat = scipy.io.loadmat(filename, chars_as_strings=False)
_vars = {}
_blocks = []
try:
fileInfo = strMatNormal(mat["Aclass"])
except KeyError:
raise Exception("File structure not supported!")
if fileInfo[1] == "1.1":
if fileInfo[3] == "binTrans":
# usually files from OpenModelica or Dymola auto saved,
# all methods rely on this structure since this was the only
# one understand by earlier versions
names = strMatTrans(mat["name"]) # names
descr = strMatTrans(mat["description"]) # descriptions
cons = mat["data_1"]
traj = mat["data_2"]
d = mat["dataInfo"][0, :]
x = mat["dataInfo"][1, :]
elif fileInfo[3] == "binNormal":
# usually files from dymola, save as...,
# variables are mapped to the structure above ('binTrans')
names = strMatNormal(mat["name"]) # names
descr = strMatNormal(mat["description"]) # descriptions
cons = mat["data_1"].T
traj = mat["data_2"].T
d = mat["dataInfo"][:, 0]
x = mat["dataInfo"][:, 1]
else:
raise Exception("File structure not supported!")
c = np.abs(x) - 1 # column
s = np.sign(x) # sign
vars = zip(names, descr, d, c, s)
elif fileInfo[1] == "1.0":
# files generated with dymola, save as..., only plotted ...
# fake the structure of a 1.1 transposed file
names = strMatNormal(mat["names"]) # names
_blocks.append(0)
mat["data_0"] = mat["data"].transpose()
del mat["data"]
_absc = (names[0], "")
for i in range(1, len(names)):
_vars[names[i]] = ("", 0, i, 1)
else:
raise Exception("File structure not supported!")
# build the SDF tree
g_root = Group("/")
ds_time = None
for name, desc, d, c, s in vars:
unit, display_unit, comment, info = _split_description(desc)
path = name.split(".")
g_parent = g_root
for segment in path[:-1]:
if segment in g_parent:
g_parent = g_parent[segment]
else:
g_child = Group(segment)
g_parent.groups.append(g_child)
g_parent = g_child
pass
if d == 1:
data = cons[c, 0] * s
else:
data = traj[c, :] * s
if "type" in info:
if info["type"] == "Integer" or "Boolean":
data = np.asarray(data, dtype=np.int32)
if d == 0:
ds = Dataset(
path[-1],
comment="Simulation time",
unit=unit,
display_unit=display_unit,
data=data,
is_scale=True,
)
ds_time = ds
elif d == 1:
ds = Dataset(
path[-1],
comment=comment,
unit=unit,
display_unit=display_unit,
data=data,
)
else:
ds = Dataset(
path[-1],
comment=comment,
unit=unit,
display_unit=display_unit,
data=data,
scales=[ds_time],
)
g_parent.datasets.append(ds)
return g_root