forked from OpenModelica/OMPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
executable file
·453 lines (378 loc) · 18.3 KB
/
Copy path__init__.py
File metadata and controls
executable file
·453 lines (378 loc) · 18.3 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# -*- coding: utf-8 -*-
"""
OMPython is a Python interface to OpenModelica.
To get started, create an OMCSession object:
from OMPython import OMCSession
OMPython = OMCSession()
OMPython.sendExpression(command)
Note: Conversion from OMPython 1.0 to OMPython 2.0 is very simple
1.0:
import OMPython
OMPython.execute(command)
2.0:
from OMPython import OMCSession
OMPython = OMCSession()
OMPython.execute(command)
The difference between execute and sendExpression is the type of the
returned expression. sendExpression maps Modelica types to Python types,
while execute tries to map also output that is not valid Modelica.
That format is harder to use.
"""
__license__ = """
This file is part of OpenModelica.
Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
c/o Linköpings universitet, Department of Computer and Information Science,
SE-58183 Linköping, Sweden.
All rights reserved.
THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE
GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
ACCORDING TO RECIPIENTS CHOICE.
The OpenModelica software and the OSMC (Open Source Modelica Consortium)
Public License (OSMC-PL) are obtained from OSMC, either from the above
address, from the URLs: http://www.openmodelica.org or
http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica
distribution. GNU version 3 is obtained from:
http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from:
http://www.opensource.org/licenses/BSD-3-Clause.
This program is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS
EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE
CONDITIONS OF OSMC-PL.
Version: 1.1
"""
import os
import sys
import time
import logging
import uuid
import getpass
import subprocess
import tempfile
import pyparsing
from distutils import spawn
if sys.platform == 'darwin':
# On Mac let's assume omc is installed here and there might be a broken omniORB installed in a bad place
sys.path.append('/opt/local/lib/python2.7/site-packages/')
sys.path.append('/opt/openmodelica/lib/python2.7/site-packages/')
# TODO: replace this with the new parser
from OMPython import OMTypedParser, OMParser
# Logger Defined
logger = logging.getLogger('OMCSession')
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
logger_console_handler = logging.StreamHandler()
logger_console_handler.setLevel(logging.INFO)
# create formatter and add it to the handlers
logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger_console_handler.setFormatter(logger_formatter)
# add the handlers to the logger
logger.addHandler(logger_console_handler)
class OMCSession(object):
def _start_server(self):
self._server = subprocess.Popen(self._omc_command, shell=True, stdout=self._omc_log_file,
stderr=self._omc_log_file)
return self._server
def _set_omc_corba_command(self, omc_path='omc'):
self._omc_command = "{0} +d=interactiveCorba +c={1}".format(omc_path, self._random_string)
return self._omc_command
def _start_omc(self):
self._server = None
self._omc_command = None
try:
self.omhome = os.environ.get('OPENMODELICAHOME')
if self.omhome is None:
self.omhome = os.path.split(os.path.split(os.path.realpath(spawn.find_executable("omc")))[0])[0]
elif os.path.exists('/opt/local/bin/omc'):
self.omhome = '/opt/local'
# add OPENMODELICAHOME\lib to PYTHONPATH so python can load omniORB libraries
sys.path.append(os.path.join(self.omhome, 'lib'))
sys.path.append(os.path.join(self.omhome, 'lib', 'python'))
# add OPENMODELICAHOME\bin to path so python can find the omniORB binaries
pathVar = os.getenv('PATH')
pathVar += ';'
pathVar += os.path.join(self.omhome, 'bin')
os.putenv('PATH', pathVar)
self._set_omc_corba_command(os.path.join(self.omhome, 'bin', 'omc'))
self._start_server()
except:
logger.error("The OpenModelica compiler is missing in the System path (%s), please install it" % os.path.join(self.omhome, 'bin', 'omc'))
raise
def _connect_to_omc(self):
self._omc = None
# import the skeletons for the global module
from omniORB import CORBA
from OMPythonIDL import _OMCIDL
# Locating and using the IOR
if sys.platform == 'win32':
self._ior_file = "openmodelica.objid." + self._random_string
else:
self._ior_file = "openmodelica." + self._currentUser + ".objid." + self._random_string
self._ior_file = os.path.join(self._temp_dir, self._ior_file)
self._omc_corba_uri = "file:///" + self._ior_file
# See if the omc server is running
if os.path.isfile(self._ior_file):
logger.info("OMC Server is up and running at {0}".format(self._omc_corba_uri))
else:
attempts = 0
while True:
if not os.path.isfile(self._ior_file):
time.sleep(0.25)
attempts += 1
if attempts == 10:
name = self._omc_log_file.name
self._omc_log_file.close()
logger.error("OMC Server is down. Please start it! Log-file says:\n%s" % open(name).read())
raise Exception
else:
continue
else:
logger.info("OMC Server is up and running at {0}".format(self._omc_corba_uri))
break
#initialize the ORB with maximum size for the ORB set
sys.argv.append("-ORBgiopMaxMsgSize")
sys.argv.append("2147483647")
self._orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
# Read the IOR file
with open(self._ior_file, 'r') as f_p:
self._ior = f_p.readline()
# Find the root POA
self._poa = self._orb.resolve_initial_references("RootPOA")
# Convert the IOR into an object reference
self._obj_reference = self._orb.string_to_object(self._ior)
# Narrow the reference to the OmcCommunication object
self._omc = self._obj_reference._narrow(_OMCIDL.OmcCommunication)
# Check if we are using the right object
if self._omc is None:
logger.error("Object reference is not valid")
raise Exception
def __init__(self, readonly=False):
self.readonly = readonly
self.omc_cache = {}
# FIXME: this code is not well written... need to be refactored
self._temp_dir = tempfile.gettempdir()
# generate a random string for this session
self._random_string = uuid.uuid4().hex
if sys.platform == 'win32':
self._omc_log_file = open(os.path.join(self._temp_dir, "openmodelica.objid." + self._random_string+".log"), 'w')
else:
self._currentUser = getpass.getuser()
if not self._currentUser:
self._currentUser = "nobody"
# this file must be closed in the destructor
self._omc_log_file = open(os.path.join(self._temp_dir, "openmodelica." + self._currentUser + ".objid." + self._random_string+".log"), 'w')
# start up omc executable, which is waiting for the CORBA connection
self._start_omc()
# connect to the running omc instance using CORBA
self._connect_to_omc()
def __del__(self):
if self._omc is not None:
self._omc.sendExpression("quit()")
self._omc_log_file.close()
# kill self._server process if it is still running/exists
if self._server.returncode is None:
self._server.kill()
# FIXME: we should have one function which interacts with OMC. Either execute OR sendExpression.
# Execute uses OMParser.check_for_values and sendExpression uses OMTypedParser.parseString.
# We should have one parser. Then we can get rid of one of these functions.
def execute(self, command):
if self._omc is not None:
result = self._omc.sendExpression(command)
if command == "quit()":
self._omc = None
return result
else:
answer = OMParser.check_for_values(result)
return answer
else:
return "No connection with OMC. Create an instance of OMCSession."
# FIXME: we should have one function which interacts with OMC. Either execute OR sendExpression.
# Execute uses OMParser.check_for_values and sendExpression uses OMTypedParser.parseString.
# We should have one parser. Then we can get rid of one of these functions.
def sendExpression(self, command, parsed=True):
"""
Sends an expression to the OpenModelica. The return type is parsed as if the
expression was part of the typed OpenModelica API (see ModelicaBuiltin.mo).
* Integer and Real are returned as Python numbers
* Strings, enumerations, and typenames are returned as Python strings
* Arrays, tuples, and MetaModelica lists are returned as tuples
* Records are returned as dicts (the name of the record is lost)
* Booleans are returned as True or False
* NONE() is returned as None
* SOME(value) is returned as value
"""
if self._omc is not None:
result = self._omc.sendExpression(str(command))
if command == "quit()":
self._omc = None
return result
else:
if (parsed==True):
answer = OMTypedParser.parseString(result)
return answer
else:
return result
else:
return "No connection with OMC. Create an instance of OMCSession."
def ask(self, question, opt=None, parsed=True):
p = (question, opt, parsed)
if self.readonly and question != 'getErrorString':
# can use cache if readonly
if p in self.omc_cache:
return self.omc_cache[p]
if opt:
expression = '{0}({1})'.format(question, opt)
else:
expression = question
logger.debug('OMC ask: {0} - parsed: {1}'.format(expression, parsed))
try:
if parsed:
res = self.execute(expression)
else:
res = self._omc.sendExpression(expression)
except Exception as e:
logger.error("OMC failed: {0}, {1}, parsed={2}".format(question, opt, parsed))
raise e
# 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('loadFile', '"{0}"'.format(filename))
def loadModel(self, className):
return self.ask('loadModel', className)
def isModel(self, className):
return self.ask('isModel', className)
def isPackage(self, className):
return self.ask('isPackage', className)
def isPrimitive(self, className):
return self.ask('isPrimitive', className)
def isConnector(self, className):
return self.ask('isConnector', className)
def isRecord(self, className):
return self.ask('isRecord', className)
def isBlock(self, className):
return self.ask('isBlock', className)
def isType(self, className):
return self.ask('isType', className)
def isFunction(self, className):
return self.ask('isFunction', className)
def isClass(self, className):
return self.ask('isClass', className)
def isParameter(self, className):
return self.ask('isParameter', className)
def isConstant(self, className):
return self.ask('isConstant', className)
def isProtected(self, className):
return self.ask('isProtected', className)
def getPackages(self):
return self.ask('getPackages')
def getPackages(self, className):
return self.ask('getPackages', className)
def getClassRestriction(self, className):
return self.ask('getClassRestriction', className)
def getDerivedClassModifierNames(self, className):
return self.ask('getDerivedClassModifierNames', className)
def getDerivedClassModifierValue(self, className, modifierName):
return self.ask('getDerivedClassModifierValue', '{0}, {1}'.format(className, modifierName))
def typeNameStrings(self, className):
return self.ask('typeNameStrings', className)
def getComponents(self, className):
return self.ask('getComponents', className)
def getClassComment(self, className):
try:
return self.ask('getClassComment', className)
except pyparsing.ParseException as ex:
logger.warning("Method 'getClassComment' failed for {0}".format(className))
logger.warning('OMTypedParser error: {0}'.format(ex.message))
return 'No description available'
def getNthComponent(self, className, comp_id):
""" returns with (type, name, description) """
return self.ask('getNthComponent', '{0}, {1}'.format(className, comp_id))
def getNthComponentAnnotation(self, className, comp_id):
return self.ask('getNthComponentAnnotation', '{0}, {1}'.format(className, comp_id))
def getImportCount(self, className):
return self.ask('getImportCount', className)
def getNthImport(self, className, importNumber):
# [Path, id, kind]
return self.ask('getNthImport', '{0}, {1}'.format(className, importNumber))
def getInheritanceCount(self, className):
return self.ask('getInheritanceCount', className)
def getNthInheritedClass(self, className, inheritanceDepth):
return self.ask('getNthInheritedClass', '{0}, {1}'.format(className, inheritanceDepth))
def getParameterNames(self, className):
try:
return self.ask('getParameterNames', className)
except KeyError as ex:
logger.warning('OMPython error: {0}'.format(ex.message))
# FIXME: OMC returns with a different structure for empty parameter set
return []
def getParameterValue(self, className, parameterName):
try:
return self.ask('getParameterValue', '{0}, {1}'.format(className, parameterName))
except pyparsing.ParseException as ex:
logger.warning('OMTypedParser error: {0}'.format(ex.message))
return ""
def getComponentModifierNames(self, className, componentName):
return self.ask('getComponentModifierNames', '{0}, {1}'.format(className, componentName))
def getComponentModifierValue(self, className, componentName):
try:
# FIXME: OMPython exception UnboundLocalError exception for 'Modelica.Fluid.Machines.ControlledPump'
return self.ask('getComponentModifierValue', '{0}, {1}'.format(className, componentName))
except pyparsing.ParseException as ex:
logger.warning('OMTypedParser error: {0}'.format(ex.message))
result = self.ask('getComponentModifierValue', '{0}, {1}'.format(className, componentName), parsed=False)
try:
answer = OMParser.check_for_values(result)
OMParser.result = {}
return answer[2:]
except (TypeError, UnboundLocalError) as ex:
logger.warning('OMParser error: {0}'.format(ex.message))
return result
def getExtendsModifierNames(self, className, componentName):
return self.ask('getExtendsModifierNames', '{0}, {1}'.format(className, componentName))
def getExtendsModifierValue(self, className, extendsName, modifierName):
try:
# FIXME: OMPython exception UnboundLocalError exception for 'Modelica.Fluid.Machines.ControlledPump'
return self.ask('getExtendsModifierValue', '{0}, {1}, {2}'.format(className, extendsName, modifierName))
except pyparsing.ParseException as ex:
logger.warning('OMTypedParser error: {0}'.format(ex.message))
result = self.ask('getExtendsModifierValue', '{0}, {1}, {2}'.format(className, extendsName, modifierName), parsed=False)
try:
answer = OMParser.check_for_values(result)
OMParser.result = {}
return answer[2:]
except (TypeError, UnboundLocalError) as ex:
logger.warning('OMParser error: {0}'.format(ex.message))
return result
def getNthComponentModification(self, className, comp_id):
# FIXME: OMPython exception Results KeyError exception
# get {$Code(....)} field
# \{\$Code\((\S*\s*)*\)\}
value = self.ask('getNthComponentModification', '{0}, {1}'.format(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):
if className:
value = self.ask('getClassNames',
'{0}, recursive={1}, qualified={2}, sort={3}, builtin={4}, showProtected={5}'.format(
className, str(recursive).lower(), str(qualified).lower(), str(sort).lower(),
str(builtin).lower(), str(showProtected).lower()))
else:
value = self.ask('getClassNames',
'recursive={1}, qualified={2}, sort={3}, builtin={4}, showProtected={5}'.format(
str(recursive).lower(), str(qualified).lower(), str(sort).lower(),
str(builtin).lower(), str(showProtected).lower()))
return value