-
Notifications
You must be signed in to change notification settings - Fork 57
/
__init__.py
executable file
·1627 lines (1454 loc) · 68.5 KB
/
__init__.py
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
OMPython is a Python interface to OpenModelica.
To get started, create an OMCSession/OMCSessionZMQ object:
from OMPython import OMCSession/OMCSessionZMQ
omc = OMCSession()/OMCSessionZMQ()
omc.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)
OMPython 3.0 includes a new class OMCSessionZMQ uses PyZMQ to communicate
with OpenModelica. A new argument `useCorba=False` is added to ModelicaSystem
class which means it will use OMCSessionZMQ by default. If you want to use
OMCSession then create ModelicaSystem object like this,
obj = ModelicaSystem(useCorba=True)
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.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from future.utils import with_metaclass
from builtins import int, range
from copy import deepcopy
from distutils import spawn
import abc
import csv
import getpass
import logging
import os
import platform
import re
import signal
import subprocess
import sys
import tempfile
import time
import uuid
import xml.etree.ElementTree as ET
from collections import OrderedDict
import numpy as np
import pyparsing
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
__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.
"""
# Logger Defined
logger = logging.getLogger('OMPython')
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 OMCSessionHelper():
def __init__(self):
# Get the path to the OMC executable, if not installed this will be None
omc_env_home = os.environ.get('OPENMODELICAHOME')
if omc_env_home:
self.omhome = omc_env_home
else:
path_to_omc = spawn.find_executable("omc")
if path_to_omc is None:
raise ValueError("Cannot find OpenModelica executable, please install from openmodelica.org")
self.omhome = os.path.split(os.path.split(os.path.realpath(path_to_omc))[0])[0]
def _get_omc_path(self):
try:
return os.path.join(self.omhome, 'bin', 'omc')
except BaseException:
logger.error("The OpenModelica compiler is missing in the System path (%s), please install it" % os.path.join(self.omhome, 'bin', 'omc'))
raise
class OMCSessionBase(with_metaclass(abc.ABCMeta, object)):
def __init__(self, readonly=False):
self.readonly = readonly
self.omc_cache = {}
self._omc_process = None
self._omc_command = None
self._omc = None
# 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
# omc log file
self._omc_log_file = None
def __del__(self):
try:
self.sendExpression("quit()")
except:
pass
self._omc_log_file.close()
if sys.version_info.major >= 3:
self._omc_process.wait(timeout=1.0)
else:
for i in range(0,100):
time.sleep(0.01)
if self._omc_process.poll() is not None:
break
# kill self._omc_process process if it is still running/exists
if self._omc_process.returncode is None:
print("OMC did not exit after being sent the quit() command; killing the process with pid=%s" % str(self._omc_process.pid))
if sys.platform=="win32":
self._omc_process.kill()
self._omc_process.wait()
else:
os.killpg(os.getpgid(self._omc_process.pid), signal.SIGTERM)
self._omc_process.kill()
self._omc_process.wait()
def _create_omc_log_file(self, suffix):
if sys.platform == 'win32':
self._omc_log_file = open(os.path.join(self._temp_dir, "openmodelica.{0}.{1}.log".format(suffix, self._random_string)), 'w')
else:
try:
self._currentUser = getpass.getuser()
if not self._currentUser:
self._currentUser = "nobody"
except KeyError:
# We are running as a uid not existing in the password database... Pretend we are nobody
self._currentUser = "nobody"
# this file must be closed in the destructor
self._omc_log_file = open(os.path.join(self._temp_dir, "openmodelica.{0}.{1}.{2}.log".format(self._currentUser, suffix, self._random_string)), 'w')
def _start_omc_process(self):
if sys.platform == 'win32':
omhome_bin = os.path.join(self.omhome, 'bin').replace("\\", "/")
my_env = os.environ.copy()
my_env["PATH"] = omhome_bin + os.pathsep + my_env["PATH"]
self._omc_process = subprocess.Popen(self._omc_command, stdout=self._omc_log_file, stderr=self._omc_log_file, env=my_env)
else:
# Because we spawned a shell, and we need to be able to kill OMC, create a new process group for this
self._omc_process = subprocess.Popen(self._omc_command, shell=True, stdout=self._omc_log_file, stderr=self._omc_log_file, preexec_fn=os.setsid)
return self._omc_process
def _set_omc_command(self, omc_path_and_args_list):
"""Define the command that will be called by the subprocess module.
On Windows, use the list input style of the subprocess module to
avoid problems resulting from spaces in the path string.
Linux, however, only works with the string version.
"""
if sys.platform == 'win32':
self._omc_command = omc_path_and_args_list
else:
self._omc_command = ' '.join(omc_path_and_args_list)
return self._omc_command
@abc.abstractmethod
def _connect_to_omc(self, timeout):
pass
# 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.
@abc.abstractmethod
def execute(self, command):
pass
def clearOMParserResult(self):
OMParser.result = {}
# 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.
@abc.abstractmethod
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
"""
pass
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.sendExpression(expression, parsed=False)
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, className="AllLoadedClasses"):
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))
# 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))
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))
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
class OMCSession(OMCSessionHelper, OMCSessionBase):
def __init__(self, readonly=False, serverFlag='--interactive=corba', timeout = 0.25):
OMCSessionHelper.__init__(self)
OMCSessionBase.__init__(self, readonly)
self._create_omc_log_file("objid")
# set omc executable path and args
self._set_omc_command([self._get_omc_path(),
serverFlag,
"+c={0}".format(self._random_string)])
# start up omc executable, which is waiting for the CORBA connection
self._start_omc_process()
# connect to the running omc instance using CORBA
self._connect_to_omc(timeout)
def __del__(self):
OMCSessionBase.__del__(self)
def _connect_to_omc(self, timeout):
# add OPENMODELICAHOME\lib\python to PYTHONPATH so python can load omniORB imports
sys.path.append(os.path.join(self.omhome, 'lib', 'python'))
# import the skeletons for the global module
try:
from omniORB import CORBA
from OMPythonIDL import _OMCIDL
except ImportError:
self._omc_process.kill()
self._omc_process.wait()
raise
# 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).replace("\\", "/")
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(timeout)
attempts += 1
if attempts == 10:
name = self._omc_log_file.name
self._omc_log_file.close()
with open(name) as fin:
contents = fin.read()
logger.error("OMC Server is down. Please start it! If the OMC version is old, try OMCSession(..., serverFlag='-d=interactiveCorba') or +d=interactiveCorba Log-file says:\n%s" % contents)
self._omc_process.kill()
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 execute(self, command):
## check for process is running
p=self._omc_process.poll()
if (p == 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 "Process Exited, No connection with OMC. Create a new instance of OMCSession"
def sendExpression(self, command, parsed=True):
## check for process is running
p=self._omc_process.poll()
if (p== None):
result = self._omc.sendExpression(str(command))
if command == "quit()":
self._omc = None
return result
else:
if parsed is True:
answer = OMTypedParser.parseString(result)
return answer
else:
return result
else:
return "Process Exited, No connection with OMC. Create a new instance of OMCSession"
class OMCSessionZMQ(OMCSessionHelper, OMCSessionBase):
def __init__(self, readonly=False, timeout = 0.25):
OMCSessionHelper.__init__(self)
OMCSessionBase.__init__(self, readonly)
self._create_omc_log_file("port")
# set omc executable path and args
self._set_omc_command([self._get_omc_path(),
"--interactive=zmq",
"+z={0}".format(self._random_string)])
# start up omc executable, which is waiting for the CORBA connection
self._start_omc_process()
# connect to the running omc instance using CORBA
self._connect_to_omc(timeout)
def __del__(self):
OMCSessionBase.__del__(self)
def _connect_to_omc(self, timeout):
# Locating and using the IOR
if sys.platform == 'win32':
self._port_file = "openmodelica.port." + self._random_string
else:
self._port_file = "openmodelica." + self._currentUser + ".port." + self._random_string
self._port_file = os.path.join(self._temp_dir, self._port_file).replace("\\", "/")
self._omc_zeromq_uri = "file:///" + self._port_file
# See if the omc server is running
attempts = 0
while True:
if not os.path.isfile(self._port_file):
time.sleep(timeout)
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("OMC Server is down. Could not open file %s" % self._port_file)
else:
continue
else:
logger.info("OMC Server is up and running at {0} pid={1}".format(self._omc_zeromq_uri, self._omc_process.pid))
break
# Read the port file
with open(self._port_file, 'r') as f_p:
self._port = f_p.readline()
# Create the ZeroMQ socket and connect to OMC server
import zmq
context = zmq.Context.instance()
self._omc = context.socket(zmq.REQ)
self._omc.setsockopt(zmq.LINGER, 0) # Dismisses pending messages if closed
self._omc.connect(self._port)
def execute(self, command):
## check for process is running
p=self._omc_process.poll()
if (p == None):
self._omc.send_string(command)
if command == "quit()":
self._omc.close()
self._omc = None
return None
else:
result = self._omc.recv_string()
answer = OMParser.check_for_values(result)
return answer
else:
return "Process Exited, No connection with OMC. Create a new instance of OMCSession"
def sendExpression(self, command, parsed=True):
## check for process is running
p=self._omc_process.poll()
if (p == None):
self._omc.send_string(str(command))
if command == "quit()":
self._omc.close()
self._omc = None
return None
else:
result = self._omc.recv_string()
if parsed is True:
answer = OMTypedParser.parseString(result)
return answer
else:
return result
else:
return "Process Exited, No connection with OMC. Create a new instance of OMCSession"
class ModelicaSystem(object):
def __init__(self, fileName=None, modelName=None, lmodel=[], useCorba=False, commandLineOptions=None): # 1
"""
"constructor"
It initializes to load file and build a model, generating object, exe, xml, mat, and json files. etc. It can be called :
•without any arguments: In this case it neither loads a file nor build a model. This is useful when a FMU needed to convert to Modelica model
•with two arguments as file name with ".mo" extension and the model name respectively
•with three arguments, the first and second are file name and model name respectively and the third arguments is Modelica standard library to load a model, which is common in such models where the model is based on the standard library. For example, here is a model named "dcmotor.mo" below table 4-2, which is located in the directory of OpenModelica at "C:\OpenModelica1.9.4-dev.beta2\share\doc\omc\testmodels".
Note: If the model file is not in the current working directory, then the path where file is located must be included together with file name. Besides, if the Modelica model contains several different models within the same package, then in order to build the specific model, in second argument, user must put the package name with dot(.) followed by specific model name.
ex: myModel = ModelicaSystem("ModelicaModel.mo", "modelName")
"""
if fileName is None and modelName is None and not lmodel: # all None
if useCorba:
self.getconn = OMCSession()
else:
self.getconn = OMCSessionZMQ()
return
if fileName is None:
return "File does not exist"
self.tree = None
self.quantitiesList=[]
self.paramlist={}
self.inputlist={}
self.outputlist={}
self.continuouslist={}
self.simulateOptions={}
self.overridevariables={}
self.simoptionsoverride={}
self.linearOptions={'startTime':0.0, 'stopTime': 1.0, 'numberOfIntervals':500, 'stepSize':0.002, 'tolerance':1e-8}
self.optimizeOptions={'startTime':0.0, 'stopTime': 1.0, 'numberOfIntervals':500, 'stepSize':0.002, 'tolerance':1e-8}
self.linearquantitiesList = [] # linearization quantity list
self.linearparameters={}
self.linearinputs = [] # linearization input list
self.linearoutputs = [] # linearization output list
self.linearstates = [] # linearization states list
if useCorba:
self.getconn = OMCSession()
else:
self.getconn = OMCSessionZMQ()
## set commandLineOptions if provided by users
if commandLineOptions is not None:
exp="".join(["setCommandLineOptions(","\"",commandLineOptions,"\"",")"])
self.getconn.sendExpression(exp)
self.xmlFile = None
self.lmodel = lmodel # may be needed if model is derived from other model
self.modelName = modelName # Model class name
self.fileName = fileName # Model file/package name
self.inputFlag = False # for model with input quantity
self.simulationFlag = False # if the model is simulated?
self.linearizationFlag = False
self.outputFlag = False
self.csvFile = '' # for storing inputs condition
self.resultfile="" # for storing result file
if not os.path.exists(self.fileName): # if file does not eixt
print("File Error:" + os.path.abspath(self.fileName) + " does not exist!!!")
return
(head, tail) = os.path.split(self.fileName) # to store directory/path and file)
self.currDir = os.getcwd()
self.modelDir = head
self.fileName_ = tail
if not self.modelDir:
file_ = os.path.exists(self.fileName_)
if (file_): # execution from path where file is located
self.__loadingModel()
else:
print("Error: File does not exist!!!")
else:
os.chdir(self.modelDir)
file_ = os.path.exists(self.fileName_)
self.model = self.fileName_[:-3]
if (self.fileName_): # execution from different path
os.chdir(self.currDir)
self.__loadingModel()
else:
print("Error: File does not exist!!!")
def __del__(self):
if self.getconn is not None:
self.requestApi('quit')
# for loading file/package, loading model and building model
def __loadingModel(self):
# load file
loadfileError = ''
loadfileResult = self.requestApi("loadFile", self.fileName)
loadfileError = self.requestApi("getErrorString")
# print the notification to users
if(loadfileResult==True and loadfileError):
print(loadfileError)
if (loadfileResult==False):
specError = 'Parser error: Unexpected token near: optimization (IDENT)'
if specError in loadfileError:
self.requestApi("setCommandLineOptions", '"+g=Optimica"')
self.requestApi("loadFile", self.fileName)
else:
print('loadFile Error: ' + loadfileError)
return
# load Modelica standard libraries or Modelica files if needed
for element in self.lmodel:
if element is not None:
loadmodelError = ''
if element.endswith(".mo"):
loadModelResult = self.requestApi("loadFile", element)
loadmodelError = self.requestApi('getErrorString')
else:
loadModelResult = self.requestApi("loadModel", element)
loadmodelError = self.requestApi('getErrorString')
if loadmodelError:
print(loadmodelError)
self.buildModel()
def buildModel(self):
# buildModelResult=self.getconn.sendExpression("buildModel("+ mName +")")
buildModelResult = self.requestApi("buildModel", self.modelName)
buildModelError = self.requestApi("getErrorString")
if ('' in buildModelResult):
print(buildModelError)
return
self.xmlFile=os.path.join(os.path.dirname(buildModelResult[0]),buildModelResult[1]).replace("\\","/")
self.xmlparse()
def sendExpression(self,expr,parsed=True):
return self.getconn.sendExpression(expr,parsed)
# request to OMC
def requestApi(self, apiName, entity=None, properties=None): # 2
if (entity is not None and properties is not None):
exp = '{}({}, {})'.format(apiName, entity, properties)
elif entity is not None and properties is None:
if (apiName == "loadFile" or apiName == "importFMU"):
exp = '{}("{}")'.format(apiName, entity)
else:
exp = '{}({})'.format(apiName, entity)
else:
exp = '{}()'.format(apiName)
try:
res = self.getconn.sendExpression(exp)
except Exception as e:
print(e)
res = None
return res
def xmlparse(self):
if(os.path.exists(self.xmlFile)):
self.tree = ET.parse(self.xmlFile)
self.root = self.tree.getroot()
rootCQ = self.root
for attr in rootCQ.iter('DefaultExperiment'):
self.simulateOptions["startTime"]= attr.get('startTime')
self.simulateOptions["stopTime"] = attr.get('stopTime')
self.simulateOptions["stepSize"] = attr.get('stepSize')
self.simulateOptions["tolerance"] = attr.get('tolerance')
self.simulateOptions["solver"] = attr.get('solver')
for sv in rootCQ.iter('ScalarVariable'):
scalar={}
scalar["name"] = sv.get('name')
scalar["changable"] = sv.get('isValueChangeable')
scalar["description"] = sv.get('description')
scalar["variability"] = sv.get('variability')
scalar["causality"] = sv.get('causality')
scalar["alias"] = sv.get('alias')
scalar["aliasvariable"] = sv.get('aliasVariable')
ch = sv.getchildren()
start = None
for att in ch:
start = att.get('start')
scalar["start"] =start
if(self.linearizationFlag==False):
if(scalar["variability"]=="parameter"):
self.paramlist[scalar["name"]]=scalar["start"]
if(scalar["variability"]=="continuous"):
self.continuouslist[scalar["name"]]=scalar["start"]
if(scalar["causality"]=="input"):
self.inputlist[scalar["name"]]=scalar["start"]
if(scalar["causality"]=="output"):
self.outputlist[scalar["name"]]=scalar["start"]
if(self.linearizationFlag==True):
if(scalar["variability"]=="parameter"):
self.linearparameters[scalar["name"]]=scalar["start"]
if(scalar["alias"]=="alias"):
name=scalar["name"]
if (name[1] == 'x'):
self.linearstates.append(name[3:-1])
if (name[1] == 'u'):
self.linearinputs.append(name[3:-1])
if (name[1] == 'y'):
self.linearoutputs.append(name[3:-1])
self.linearquantitiesList.append(scalar)
else:
self.quantitiesList.append(scalar)
else:
print("Error: ! XML file not generated")
return
def getQuantities(self, names=None): # 3
"""
This method returns list of dictionaries. It displays details of quantities such as name, value, changeable, and description, where changeable means if value for corresponding quantity name is changeable or not. It can be called :
usage:
>>> getQuantities()
>>> getQuantities("Name1")
>>> getQuantities(["Name1","Name2"])
"""
if(names==None):
return self.quantitiesList
elif(isinstance(names, str)):
return [x for x in self.quantitiesList if x["name"] == names]
elif isinstance(names, list):
return [x for y in names for x in self.quantitiesList if x["name"]==y]
def getContinuous(self, names=None): # 4
"""
This method returns dict. The key is continuous names and value is corresponding continuous value.
usage:
>>> getContinuous()
>>> getContinuous("Name1")
>>> getContinuous(["Name1","Name2"])
"""
if not self.simulationFlag:
if(names==None):
return self.continuouslist
elif(isinstance(names, str)):
return [self.continuouslist.get(names ,"NotExist")]
elif(isinstance(names, list)):
return ([self.continuouslist.get(x ,"NotExist") for x in names])
else:
if(names==None):
for i in self.continuouslist:
try:
value = self.getSolutions(i)
self.continuouslist[i]=value[0][-1]
except Exception:
print(i,"could not be computed")
return self.continuouslist
elif(isinstance(names, str)):
if names in self.continuouslist:
value = self.getSolutions(names)
self.continuouslist[names]=value[0][-1]
return [self.continuouslist.get(names)]
else:
return (names, " is not continuous")
elif(isinstance(names, list)):
valuelist=[]
for i in names:
if i in self.continuouslist:
value=self.getSolutions(i)
self.continuouslist[i]=value[0][-1]
valuelist.append(value[0][-1])
else:
return (i," is not continuous")
return valuelist
def getParameters(self, names=None): # 5
"""
This method returns dict. The key is parameter names and value is corresponding parameter value.
If name is None then the function will return dict which contain all parameter names as key and value as corresponding values.
usage:
>>> getParameters()
>>> getParameters("Name1")
>>> getParameters(["Name1","Name2"])
"""
if(names==None):
return self.paramlist
elif(isinstance(names, str)):
return [self.paramlist.get(names,"NotExist")]
elif(isinstance(names, list)):
return ([self.paramlist.get(x,"NotExist") for x in names])
def getlinearParameters(self, names=None): # 5
"""
This method returns dict. The key is parameter names and value is corresponding parameter value.
If *name is None then the function will return dict which contain all parameter names as key and value as corresponding values. eg., getParameters()
Otherwise variable number of arguments can be passed as parameter name in string format separated by commas. eg., getParameters('paraName1', 'paraName2')
"""
if(names==0):
return self.linearparameters
elif(isinstance(names, str)):
return [self.linearparameters.get(names,"NotExist")]
else:
return ([self.linearparameters.get(x,"NotExist") for x in names])
def getInputs(self, names=None): # 6
"""
This method returns dict. The key is input names and value is corresponding input value.
If *name is None then the function will return dict which contain all input names as key and value as corresponding values. eg., getInputs()
Otherwise variable number of arguments can be passed as input name in string format separated by commas. eg., getInputs('iName1', 'iName2')
"""
if(names==None):
return self.inputlist
elif(isinstance(names, str)):
return [self.inputlist.get(names,"NotExist")]
elif(isinstance(names, list)):
return ([self.inputlist.get(x,"NotExist") for x in names])
def getOutputs(self, names=None): # 7
"""
This method returns dict. The key is output names and value is corresponding output value.
If name is None then the function will return dict which contain all output names as key and value as corresponding values. eg., getOutputs()
usage:
>>> getOutputs()
>>> getOutputs("Name1")
>>> getOutputs(["Name1","Name2"])
"""
if not self.simulationFlag:
if(names==None):
return self.outputlist
elif(isinstance(names, str)):
return [self.outputlist.get(names,"NotExist")]
else:
return ([self.outputlist.get(x,"NotExist") for x in names])
else:
if (names== None):
for i in self.outputlist:
value = self.getSolutions(i)
self.outputlist[i]=value[0][-1]
return self.outputlist
elif(isinstance(names, str)):
if names in self.outputlist:
value = self.getSolutions(names)
self.outputlist[names]=value[0][-1]
return [self.outputlist.get(names)]
else:
return (names, " is not Output")
elif(isinstance(names, list)):
valuelist=[]
for i in names:
if i in self.outputlist:
value=self.getSolutions(i)
self.outputlist[i]=value[0][-1]
valuelist.append(value[0][-1])
else:
return (i, "is not Output")
return valuelist
def getSimulationOptions(self, names=None): # 8
"""
This method returns dict. The key is simulation option names and value is corresponding simulation option value.
If name is None then the function will return dict which contain all simulation option names as key and value as corresponding values. eg., getSimulationOptions()
usage:
>>> getSimulationOptions()
>>> getSimulationOptions("Name1")
>>> getSimulationOptions(["Name1","Name2"])
"""