-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathOMCSession.py
More file actions
337 lines (258 loc) · 12.2 KB
/
Copy pathOMCSession.py
File metadata and controls
337 lines (258 loc) · 12.2 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# -*- coding: utf-8 -*-
"""
Definition of an OMC session.
"""
from __future__ import annotations
import logging
from typing import Any, Optional
import warnings
import pyparsing
from OMPython.om_session_abc import (
OMPathABC,
OMSessionABC,
OMSessionException,
)
from OMPython.om_session_omc import (
OMCSessionABC,
OMCSessionDocker,
OMCSessionDockerContainer,
OMCSessionLocal,
OMCSessionPort,
OMCSessionWSL,
)
from OMPython.compatibility_v400 import (
depreciated_class,
)
# define logger using the current module name as ID
logger = logging.getLogger(__name__)
@depreciated_class(msg="Please use class OMSessionException instead!")
class OMCSessionException(OMSessionException):
"""
Just a compatibility layer ...
"""
@depreciated_class(msg="Please use OMCSession*.sendExpression(...) instead!")
class OMCSessionCmd:
"""
Implementation of Open Modelica Compiler API functions. Depreciated!
"""
def __init__(self, session: OMSessionABC, readonly: bool = False):
if not isinstance(session, OMSessionABC):
raise OMCSessionException("Invalid OMC process definition!")
self._session = session
self._readonly = readonly
self._omc_cache: dict[tuple[str, bool], Any] = {}
def _ask(self, question: str, opt: Optional[list[str]] = None, parsed: bool = True):
if opt is None:
expression = question
elif isinstance(opt, list):
expression = f"{question}({','.join([str(x) for x in opt])})"
else:
raise OMSessionException(f"Invalid definition of options for {repr(question)}: {repr(opt)}")
p = (expression, parsed)
if self._readonly and question != 'getErrorString':
# can use cache if readonly
if p in self._omc_cache:
return self._omc_cache[p]
try:
res = self._session.sendExpression(expression, parsed=parsed)
except OMSessionException as ex:
raise OMSessionException(f"OMC _ask() failed: {expression} (parsed={parsed})") from ex
# save response
self._omc_cache[p] = res
return res
# TODO: Open Modelica Compiler API functions. Would be nice to generate these.
def loadFile(self, filename):
return self._ask(question='loadFile', opt=[f'"{filename}"'])
def loadModel(self, className):
return self._ask(question='loadModel', opt=[className])
def isModel(self, className):
return self._ask(question='isModel', opt=[className])
def isPackage(self, className):
return self._ask(question='isPackage', opt=[className])
def isPrimitive(self, className):
return self._ask(question='isPrimitive', opt=[className])
def isConnector(self, className):
return self._ask(question='isConnector', opt=[className])
def isRecord(self, className):
return self._ask(question='isRecord', opt=[className])
def isBlock(self, className):
return self._ask(question='isBlock', opt=[className])
def isType(self, className):
return self._ask(question='isType', opt=[className])
def isFunction(self, className):
return self._ask(question='isFunction', opt=[className])
def isClass(self, className):
return self._ask(question='isClass', opt=[className])
def isParameter(self, className):
return self._ask(question='isParameter', opt=[className])
def isConstant(self, className):
return self._ask(question='isConstant', opt=[className])
def isProtected(self, className):
return self._ask(question='isProtected', opt=[className])
def getPackages(self, className="AllLoadedClasses"):
return self._ask(question='getPackages', opt=[className])
def getClassRestriction(self, className):
return self._ask(question='getClassRestriction', opt=[className])
def getDerivedClassModifierNames(self, className):
return self._ask(question='getDerivedClassModifierNames', opt=[className])
def getDerivedClassModifierValue(self, className, modifierName):
return self._ask(question='getDerivedClassModifierValue', opt=[className, modifierName])
def typeNameStrings(self, className):
return self._ask(question='typeNameStrings', opt=[className])
def getComponents(self, className):
return self._ask(question='getComponents', opt=[className])
def getClassComment(self, className):
try:
return self._ask(question='getClassComment', opt=[className])
except pyparsing.ParseException as ex:
logger.warning("Method 'getClassComment(%s)' failed; OMTypedParser error: %s",
className, ex.msg)
return 'No description available'
def getNthComponent(self, className, comp_id):
""" returns with (type, name, description) """
return self._ask(question='getNthComponent', opt=[className, comp_id])
def getNthComponentAnnotation(self, className, comp_id):
return self._ask(question='getNthComponentAnnotation', opt=[className, comp_id])
def getImportCount(self, className):
return self._ask(question='getImportCount', opt=[className])
def getNthImport(self, className, importNumber):
# [Path, id, kind]
return self._ask(question='getNthImport', opt=[className, importNumber])
def getInheritanceCount(self, className):
return self._ask(question='getInheritanceCount', opt=[className])
def getNthInheritedClass(self, className, inheritanceDepth):
return self._ask(question='getNthInheritedClass', opt=[className, inheritanceDepth])
def getParameterNames(self, className):
try:
return self._ask(question='getParameterNames', opt=[className])
except KeyError as ex:
logger.warning('OMPython error: %s', ex)
# FIXME: OMC returns with a different structure for empty parameter set
return []
def getParameterValue(self, className, parameterName):
try:
return self._ask(question='getParameterValue', opt=[className, parameterName])
except pyparsing.ParseException as ex:
logger.warning("Method 'getParameterValue(%s, %s)' failed; OMTypedParser error: %s",
className, parameterName, ex.msg)
return ""
def getComponentModifierNames(self, className, componentName):
return self._ask(question='getComponentModifierNames', opt=[className, componentName])
def getComponentModifierValue(self, className, componentName):
return self._ask(question='getComponentModifierValue', opt=[className, componentName])
def getExtendsModifierNames(self, className, componentName):
return self._ask(question='getExtendsModifierNames', opt=[className, componentName])
def getExtendsModifierValue(self, className, extendsName, modifierName):
return self._ask(question='getExtendsModifierValue', opt=[className, extendsName, modifierName])
def getNthComponentModification(self, className, comp_id):
# FIXME: OMPython exception Results KeyError exception
# get {$Code(....)} field
# \{\$Code\((\S*\s*)*\)\}
value = self._ask(question='getNthComponentModification', opt=[className, comp_id], parsed=False)
value = value.replace("{$Code(", "")
return value[:-3]
# return self.re_Code.findall(value)
# function getClassNames
# input TypeName class_ = $Code(AllLoadedClasses);
# input Boolean recursive = false;
# input Boolean qualified = false;
# input Boolean sort = false;
# input Boolean builtin = false "List also builtin classes if true";
# input Boolean showProtected = false "List also protected classes if true";
# output TypeName classNames[:];
# end getClassNames;
def getClassNames(self, className=None, recursive=False, qualified=False, sort=False, builtin=False,
showProtected=False):
opt = [className] if className else [] + [f'recursive={str(recursive).lower()}',
f'qualified={str(qualified).lower()}',
f'sort={str(sort).lower()}',
f'builtin={str(builtin).lower()}',
f'showProtected={str(showProtected).lower()}']
return self._ask(question='getClassNames', opt=opt)
@depreciated_class(msg="Please use OMCSession* classes instead!")
class OMCSessionZMQ(OMSessionABC):
"""
This class is a compatibility layer for the new schema using OMCSession* classes.
"""
def __init__(
self,
timeout: Optional[float] = None,
omhome: Optional[str] = None,
omc_process: Optional[OMCSessionABC] = None,
) -> None:
"""
Initialisation for OMCSessionZMQ
"""
if omc_process is None:
omc_process = OMCSessionLocal(omhome=omhome, timeout=timeout)
elif not isinstance(omc_process, OMCSessionABC):
raise OMSessionException("Invalid definition of the OMC process!")
self.omc_process = omc_process
super().__init__(timeout=timeout)
def __del__(self):
if hasattr(self, 'omc_process'):
del self.omc_process
@staticmethod
def escape_str(value: str) -> str:
"""
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
"""
return OMCSessionABC.escape_str(value=value)
def omcpath(self, *path) -> OMPathABC:
"""
Create an OMCPath object based on the given path segments and the current OMC process definition.
"""
return self.omc_process.omcpath(*path)
def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC:
"""
Get a temporary directory using OMC. It is our own implementation as non-local usage relies on OMC to run all
filesystem related access.
"""
return self.omc_process.omcpath_tempdir(tempdir_base=tempdir_base)
def execute(self, command: str):
warnings.warn(
message="This function is depreciated and will be removed in future versions; "
"please use sendExpression() instead",
category=DeprecationWarning,
stacklevel=2,
)
return self.omc_process.sendExpression(expr=command, parsed=False)
def sendExpression(self, command: str, parsed: bool = True) -> Any: # pylint: disable=W0237
"""
Send an expression to the OMC server and return the result.
The complete error handling of the OMC result is done within this method using 'getMessagesStringInternal()'.
Caller should only check for OMCSessionException.
Compatibility: 'command' was renamed to 'expr'
"""
return self.omc_process.sendExpression(expr=command, parsed=parsed)
def get_version(self) -> str:
return self.omc_process.get_version()
def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]:
return self.omc_process.model_execution_prefix(cwd=cwd)
def set_workdir(self, workdir: OMPathABC) -> None:
return self.omc_process.set_workdir(workdir=workdir)
@depreciated_class(msg="Please use class OMCSessionLocal instead!")
class OMCProcessLocal(OMCSessionLocal):
"""
Just a wrapper class; OMCProcessLocal => OMCSessionLocal
"""
@depreciated_class(msg="Please use class OMCSessionPort instead!")
class OMCProcessPort(OMCSessionPort):
"""
Just a wrapper class; OMCProcessPort => OMCSessionPort
"""
@depreciated_class(msg="Please use class OMCSessionDocker instead!")
class OMCProcessDocker(OMCSessionDocker):
"""
Just a wrapper class; OMCProcessDocker => OMCSessionDocker
"""
@depreciated_class(msg="Please use class OMCSessionDockerContainer instead!")
class OMCProcessDockerContainer(OMCSessionDockerContainer):
"""
Just a wrapper class; OMCProcessDockerContainer => OMCSessionDockerContainer
"""
@depreciated_class(msg="Please use class OMCSessionWSL instead!")
class OMCProcessWSL(OMCSessionWSL):
"""
Just a wrapper class; OMCProcessWSL => OMCSessionWSL
"""