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
·1659 lines (1466 loc) · 73.3 KB
/
Copy path__init__.py
File metadata and controls
executable file
·1659 lines (1466 loc) · 73.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
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 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
# The following import are added by Sudeep
import platform
import numpy as np
import csv
from copy import deepcopy
import xml.etree.ElementTree as ET
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\python to PYTHONPATH so python can load omniORB imports
sys.path.append(os.path.join(self.omhome, 'lib', 'python'))
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).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(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
#author = Sudeep Bajracharya
#sudba156@student.liu.se
#LIU(Department of Computer Science)
class Quantity:
"""
To represent quantities details
"""
def __init__(self, name, start, changable, variability, description, causality, alias, aliasvariable):
self.name = name
self.start = start
self.changable = changable
self.description = description
self.variability = variability
self.causality = causality
self.alias = alias
self.aliasvariable = aliasvariable
class ModelicaSystem(object):
def __init__(self, fileName = None, modelName = None, lmodel = 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 lmodel is None: # all None
self.getconn = OMCSession()
return
if fileName is None:
return "File does not exist"
self.tree = None
self.linearquantitiesList=[] #linearization quantity list
self.linearinputs=[] #linearization input list
self.linearoutputs=[] #linearization output list
self.linearstates=[] #linearization states list
self.quantitiesList = [] #detail list of all Modelica quantity variables inc. name, changable, description, etc
self.qNamesList = [] #for all quantities name list
self.cNamesList = [] #for continuous quantities name list
self.cValuesList = [] #for continuous quantities value list
self.iNamesList = [] #for input quantities name list
self.inputsVal = [] #for input quantities value list
self.specialNames = []
self.oNamesList = [] #for output quantities name list
self.pNamesList = [] #for parameter quantities name list
self.pValuesList = [] #for parameter quantities value list
self.oValuesList = [] #for output quantities value list
self.simNamesList = ['startTime', 'stopTime', 'stepSize', 'tolerance', 'solver'] #simulation options list
self.simValuesList = [] #for simulation values list
self.optimizeOptionsNamesList = ['startTime', 'stopTime', 'numberOfIntervals', 'stepSize', 'tolerance']
self.optimizeOptionsValuesList = [0.0, 1.0, 500, 0.002,1e-8]
self.linearizeOptionsNamesList = ['startTime', 'stopTime', 'numberOfIntervals', 'stepSize', 'tolerance']
self.linearizeOptionsValuesList = [0.0, 1.0, 500, 0.002,1e-8]
self.getconn = OMCSession()
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
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(self.fileName_, self.modelName, self.lmodel)
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(self.fileName, self.modelName, self.lmodel)
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, fName, mName, lmodel):
#load file
loadfileError = ''
loadfileResult = self.requestApi("loadFile", fName)
loadfileError = self.requestApi("getErrorString")
if loadfileError:
specError = 'Parser error: Unexpected token near: optimization (IDENT)'
if specError in loadfileError:
self.requestApi("setCommandLineOptions", '"+g=Optimica"')
self.requestApi("loadFile", fName)
else:
print ('loadFile Error: ' + loadfileError)
return
#load Modelica standard libraries if needed
if lmodel is not None:
loadmodelError = ''
loadModelResult = self.requestApi("loadModel", lmodel)
loadmodelError = self.requestApi('getErrorString')
if loadmodelError:
print (loadmodelError)
return
# build model
#buildModelError = ''
self.getconn.sendExpression("setCommandLineOptions(\"+d=initialization\")")
#buildModelResult=self.getconn.sendExpression("buildModel("+ mName +")")
buildModelResult = self.requestApi("buildModel", mName)
buildModelError = self.requestApi("getErrorString")
if ('' in buildModelResult):
print (buildModelError)
return
self.xmlFile = buildModelResult[1]
self.tree = ET.parse(self.xmlFile)
self.root = self.tree.getroot()
self.__createQuantitiesList() #initialize quantitiesList
self.__getQuantitiesNames() #initialize qNamesList
self.__getContinuousNames() #initialize cNamesList
self.__getParameterNames() #initialize pNamesList
self.__getInputNames() #initialize iNamesList
self.__setInputSize() #defing input value list size
self.__getOutputNames() #initialize oNamesList
self.__getContinuousValues() #initialize cValuesList
self.__getParameterValues() #initialize pValuesList
self.__getInputValues() #initialize input value list
self.__getOutputValues() #initialize oValuesList
self.__getSimulationValues() #initialize simulation value list
#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
#create detail quantities list
def __createQuantitiesList(self):
rootCQ = self.root
if not self.quantitiesList:
for sv in rootCQ.iter('ScalarVariable'):
name = sv.get('name')
changable = sv.get('isValueChangeable')
description = sv.get('description')
variability = sv.get('variability')
causality = sv.get('causality')
alias = sv.get('alias')
aliasvariable = sv.get('aliasVariable')
ch = sv.getchildren()
start = None
for att in ch:
start = att.get('start')
self.quantitiesList.append(Quantity(name, start, changable, variability, description, causality,alias,aliasvariable))
return self.quantitiesList
#to get list of all quantities names
def __getQuantitiesNames(self):
if not self.qNamesList:
for q in self.quantitiesList:
self.qNamesList.append(q.name)
return self.qNamesList
#check if names exist
def __checkAvailability(self, names, chkList, inputFlag = None):
try:
if isinstance(names, list):
nonExistingList = []
for n in names:
if n not in chkList:
nonExistingList.append(n)
if nonExistingList:
print ('Error!!! ' + str(nonExistingList) + ' does not exist.')
return False
elif isinstance(names, str):
if names not in chkList:
print ('Error!!! ' + names + ' does not exist.')
return False
else:
print ('Error!!! Incorrect format')
return False
return True
except Exception as e:
print (e)
#to get details of quantities names
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 :
•without argument: it returns list of dictionaries of all quantities
•with a single argument as list of quantities name in string format: it returns list of dictionaries of only particular quantities name
•a single argument as a single quantity name (or in list) in string format: it returns list of dictionaries of the particular quantity name
"""
try:
if names is not None:
checking = self.__checkAvailability(names, self.qNamesList)
if not checking:
return
if isinstance(names, str):
qlistnames = []
for q in self.quantitiesList:
if names == q.name:
qlistnames.append({'Name':q.name, 'Value':q.start,'Changeable' : q.changable, 'Variability': q.variability, 'alias':q.alias,'aliasvariable':q.aliasvariable, 'Description':q.description})
break
return qlistnames
elif isinstance(names, list):
qlist = []
for n in names:
for q in self.quantitiesList:
if n == q.name:
qlist.append({'Name':q.name, 'Value':q.start,'Changeable' : q.changable, 'Variability': q.variability,'alias':q.alias,'aliasvariable':q.aliasvariable, 'Description':q.description})
break
return qlist
else:
print ('Error!!! Incorrect format')
else:
qlist = []
for q in self.quantitiesList:
qlist.append({'Name':q.name, 'Value':q.start,'Changeable' : q.changable, 'Variability': q.variability, 'alias':q.alias,'aliasvariable':q.aliasvariable,'Description':q.description})
return qlist
except Exception as e:
print (e)
#to get list of quantities name that are continuous variability
def __getContinuousNames(self):
"""
This method returns list of quantities name that are continuous. It can be called:
•only without any arguments: returns the list of quantities (continuous) names
"""
if not self.cNamesList:
for l in self.quantitiesList:
if(l.variability == "continuous"):
self.cNamesList.append(l.name)
return self.cNamesList
def __checkTuple(self, names, chkList, inputFlag=None):
if isinstance(names, tuple) and (len(n) == 1 for n in names):
nonExistingList = []
for n in names:
if n not in chkList:
nonExistingList.append(n)
if nonExistingList:
print ('Error!!!' + str(nonExistingList) + ' does not exist.')
return False
return True
else:
print ('Error!!! Incorrect format')
return False
def getContinuous(self, *names):#4
"""
This method returns dict. The key is continuous names and value is corresponding continuous value.
If *name is None then the function will return dict which contain all continuous names as key and value as corresponding values. eg., getContinuous()
Otherwise variable number of arguments can be passed as continuous name in string format separated by commas. eg., getContinuous('cName1', 'cName2')
"""
try:
if not self.simulationFlag:
return self.__getXXXs(names, self.__getContinuousNames(), self.__getContinuousValues())
else:
if len(names) == 0:
cQuantities = self.__getContinuousNames()
cTuple = tuple(cQuantities)
cSol = self.getSolutions(cTuple)
cDict = dict()
for name, val in zip(cQuantities, cSol):
cDict[name] = val[-1]
return cDict
else:
checking = self.__checkTuple(names, self.__getContinuousNames())
if not checking:
return
cSol = self.getSolutions(names)
cList = list()
for val in cSol:
cList.append(val[-1])
tupVal = tuple(cList)
if len(tupVal) == 1:
tupVal, = tupVal
return tupVal
except Exception:
if pyparsing.ParseException:
print ('Error!!! Name does not exist or incorrect format ')
else:
raise
def getParameters(self, *names):#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')
"""
return self.__getXXXs(names, self.__getParameterNames(), self.__getParameterValues())
def getInputs(self, *names):#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')
"""
return self.__getXXXs(names, self.__getInputNames(), self.__getInputValues())
def getOutputs(self, *names):#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()
Otherwise variable number of arguments can be passed as output name in string format separated by commas. eg., getOutputs(opName1', 'opName2')
"""
try:
if not self.simulationFlag:
return self.__getXXXs(names, self.__getOutputNames(), self.__getOutputValues())
else:
if len(names) == 0:
op = self.__getOutputNames()
opTuple = tuple(op)
opSol = self.getSolutions(opTuple)
opDict = dict()
for name, val in zip(op, opSol):
opDict[name] = val[-1]
return opDict
else:
checking = self.__checkTuple(names, self.__getOutputNames())
if not checking:
return
opSol = self.getSolutions(names)
opList = list()
for val in opSol:
opList.append(val[-1])
tupVal = tuple(opList)
if len(tupVal) == 1:
tupVal, = tupVal
return tupVal
# else:
# print ('The model is not simulated yet!!!')
except Exception:
if pyparsing.ParseException:
print ('Error!!! Name does not exist or incorrect format ')
else:
raise
def __getParameterNames(self):
"""
This method returns list of quantities name that are parameters. It can be called:
•only without any arguments: returns list of quantities (parameter) name
"""
if not self.pNamesList:
for l in self.quantitiesList:
if(l.variability == "parameter"):
self.pNamesList.append(l.name)
return self.pNamesList
#to get list of quantities name that are input
def __getInputNames(self):
"""
This method returns list of quantities name that are inputs. It can be called:
•only without any arguments: returns the list of quantities (input) name
"""
if not self.iNamesList:
for l in self.quantitiesList:
if(l.causality == "input"):
self.iNamesList.append(l.name)
return self.iNamesList
#set input value list size
def __setInputSize(self):
size = len(self.__getInputNames())
self.inputsVal = [None]*size
#to get list of quantities name that are output
#Todo: has not been tested yet due to lack of the model that contains output.
def __getOutputNames(self):
"""
This method returns list of quantities name that are outputs. It can be called:
•only without any arguments: returns the list of all quantities (output) name
Note: Test has not been carried out for Output quantities due to the lack of model that contains output
"""
if not self.oNamesList:
for l in self.quantitiesList:
if(l.causality == "output"):
self.oNamesList.append(l.name)
return self.oNamesList
#to get values of continuous quantities name
def __getContinuousValues(self, contiName=None):
"""
This method returns list of values of the quantities name that are continuous. It can be called:
•without any arguments: returns list of values of all quantities name that are continuous
•with a single argument as continuous name in string format: returns value of the corresponding name
•with a single argument as list of continuous names in string format: return list of values of the corresponding names.
1.If the list of names is more than one and it is being assigned by single variable then it returns the list of values of the corresponding names.
2.If the list of names is more than one and it is being assigned by same number of variable as the number of element in the list then it will return the value to the variables correspondingly (python unpacking)
"""
if contiName is None:
if not self.cValuesList:
for l in self.quantitiesList:
if(l.variability == "continuous"):
str_ = l.start
if str_ is None:
self.cValuesList.append(str_)
else:
self.cValuesList.append(float(str_))
return self.cValuesList
else:
try:
#if isinstance(contiName, list):
checking = self.__checkAvailability(contiName, self.__getContinuousNames())
#if checking is False:
if not checking:
return
if isinstance (contiName, str):
index_ = self.cNamesList.index(contiName)
return (self.cValuesList[index_])
valList = []
for n in contiName:
index_ = self.cNamesList.index(n)
valList.append(self.cValuesList[index_])
return valList
except Exception as e:
print (e)
#to get values of parameter quantities name
def __getParameterValues(self, paraName = None):
"""
This method returns list of values of the quantities name that are parameters. It can be called:
•without any arguments: return list of values of all quantities (parameter) name
•with a single argument as parameter name in string format: returns value of the corresponding name
•with a single argument as list of parameter names in string format: return list of values of the corresponding names.
1.If the list of names is more than one and it is being assigned by single variable then it returns the list of values of the corresponding names
2.If the list of names is more than one and it is being assigned by same number of variable as the number of element in the list then it will return the value to the variables correspondingly (python unpacking)
"""
if paraName is None:
if not self.pValuesList:
for l in self.quantitiesList:
if(l.variability == "parameter"):
str_ = l.start
if ((str_ is None) or (str_ == 'true' or str_ == 'false')):
if (str_ == 'true'):
str_ = True
elif str_ == 'false':
str_ = False
self.pValuesList.append(str_)
else:
self.pValuesList.append(float(str_))
return self.pValuesList
else:
try:
checking = self.__checkAvailability(paraName, self.__getParameterNames())
if not checking:
return
if isinstance(paraName, str):
index_ = self.pNamesList.index(paraName)
return (self.pValuesList[index_])
valList = []
for n in paraName:
index_ = self.pNamesList.index(n)
valList.append(self.pValuesList[index_])
return valList
except Exception as e:
print (e)
#to get values of input names
def __getInputValues(self, iName=None):
"""
This method returns list of values of the quantities name that are inputs. It can be called:
•without any arguments: returns list of values of all quantities (input) name
•with a single argument as input name in string format: returns list of values of the corresponding name
"""
try:
if iName is None:
return self.inputsVal
elif isinstance(iName, str):
checking = self.__checkAvailability(iName,self.__getInputNames())
if not checking:
return
index_ = self.iNamesList.index(iName)
return self.inputsVal[index_]
else:
print ('Error!!! Incorrect format')
except Exception as e:
print (e)
#to get values of output quantities name
#Todo: has not been tested yet due to lack of the model that contains output.
def __getOutputValues(self):
"""
This method returns list of values of the quantities name that are outputs. It can be called:
•only without any arguments: returns the list of values of all output name
Note: Test has not been carried out for Output quantities due to the lack of model that contains output
"""
if not self.oValuesList:
for l in self.quantitiesList:
if(l.causality == "output"):
self.oValuesList.append(l.start)
return self.oValuesList