forked from OpenModelica/OMPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelicaSystem.py
More file actions
1530 lines (1284 loc) · 62.6 KB
/
ModelicaSystem.py
File metadata and controls
1530 lines (1284 loc) · 62.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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 -*-
"""
Definition of main class to run Modelica simulations - ModelicaSystem.
"""
__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.
"""
import csv
from dataclasses import dataclass
import importlib
import logging
import numbers
import numpy as np
import os
import pathlib
import platform
import re
import subprocess
import tempfile
import textwrap
from typing import Optional, Any
import warnings
import xml.etree.ElementTree as ET
from OMPython.OMCSession import OMCSessionException, OMCSessionZMQ, OMCProcessLocal
# define logger using the current module name as ID
logger = logging.getLogger(__name__)
class ModelicaSystemError(Exception):
"""
Exception used in ModelicaSystem and ModelicaSystemCmd classes.
"""
@dataclass
class LinearizationResult:
"""Modelica model linearization results.
Attributes:
n: number of states
m: number of inputs
p: number of outputs
A: state matrix (n x n)
B: input matrix (n x m)
C: output matrix (p x n)
D: feedthrough matrix (p x m)
x0: fixed point
u0: input corresponding to the fixed point
stateVars: names of state variables
inputVars: names of inputs
outputVars: names of outputs
"""
n: int
m: int
p: int
A: list
B: list
C: list
D: list
x0: list[float]
u0: list[float]
stateVars: list[str]
inputVars: list[str]
outputVars: list[str]
def __iter__(self):
"""Allow unpacking A, B, C, D = result."""
yield self.A
yield self.B
yield self.C
yield self.D
def __getitem__(self, index: int):
"""Allow accessing A, B, C, D via result[0] through result[3].
This is needed for backwards compatibility, because
ModelicaSystem.linearize() used to return [A, B, C, D].
"""
return {0: self.A, 1: self.B, 2: self.C, 3: self.D}[index]
class ModelicaSystemCmd:
"""A compiled model executable."""
def __init__(self, runpath: pathlib.Path, modelname: str, timeout: Optional[float] = None) -> None:
self._runpath = pathlib.Path(runpath).resolve().absolute()
self._model_name = modelname
self._timeout = timeout
self._args: dict[str, str | None] = {}
self._arg_override: dict[str, str] = {}
def arg_set(self, key: str, val: Optional[str | dict] = None) -> None:
"""
Set one argument for the executable model.
Parameters
----------
key : str
val : str, None
"""
if not isinstance(key, str):
raise ModelicaSystemError(f"Invalid argument key: {repr(key)} (type: {type(key)})")
key = key.strip()
if val is None:
argval = None
elif isinstance(val, str):
argval = val.strip()
elif isinstance(val, numbers.Number):
argval = str(val)
elif key == 'override' and isinstance(val, dict):
for okey in val:
if not isinstance(okey, str) or not isinstance(val[okey], (str, numbers.Number)):
raise ModelicaSystemError("Invalid argument for 'override': "
f"{repr(okey)} = {repr(val[okey])}")
self._arg_override[okey] = val[okey]
argval = ','.join([f"{okey}={str(self._arg_override[okey])}" for okey in self._arg_override])
else:
raise ModelicaSystemError(f"Invalid argument value for {repr(key)}: {repr(val)} (type: {type(val)})")
if key in self._args:
logger.warning(f"Overwrite model executable argument: {repr(key)} = {repr(argval)} "
f"(was: {repr(self._args[key])})")
self._args[key] = argval
def arg_get(self, key: str) -> Optional[str | dict]:
"""
Return the value for the given key
"""
if key in self._args:
return self._args[key]
return None
def args_set(self, args: dict[str, Optional[str | dict[str, str]]]) -> None:
"""
Define arguments for the model executable.
Parameters
----------
args : dict[str, Optional[str | dict[str, str]]]
"""
for arg in args:
self.arg_set(key=arg, val=args[arg])
def get_exe(self) -> pathlib.Path:
"""Get the path to the compiled model executable."""
if platform.system() == "Windows":
path_exe = self._runpath / f"{self._model_name}.exe"
else:
path_exe = self._runpath / self._model_name
if not path_exe.exists():
raise ModelicaSystemError(f"Application file path not found: {path_exe}")
return path_exe
def get_cmd(self) -> list:
"""Get a list with the path to the executable and all command line args.
This can later be used as an argument for subprocess.run().
"""
path_exe = self.get_exe()
cmdl = [path_exe.as_posix()]
for key in self._args:
if self._args[key] is None:
cmdl.append(f"-{key}")
else:
cmdl.append(f"-{key}={self._args[key]}")
return cmdl
def run(self) -> int:
"""Run the requested simulation.
Returns
-------
Subprocess return code (0 on success).
"""
cmdl: list = self.get_cmd()
logger.debug("Run OM command %s in %s", repr(cmdl), self._runpath.as_posix())
if platform.system() == "Windows":
path_dll = ""
# set the process environment from the generated .bat file in windows which should have all the dependencies
path_bat = self._runpath / f"{self._model_name}.bat"
if not path_bat.exists():
raise ModelicaSystemError("Batch file (*.bat) does not exist " + str(path_bat))
with open(file=path_bat, mode='r', encoding='utf-8') as fh:
for line in fh:
match = re.match(r"^SET PATH=([^%]*)", line, re.IGNORECASE)
if match:
path_dll = match.group(1).strip(';') # Remove any trailing semicolons
my_env = os.environ.copy()
my_env["PATH"] = path_dll + os.pathsep + my_env["PATH"]
else:
# TODO: how to handle path to resources of external libraries for any system not Windows?
my_env = None
try:
cmdres = subprocess.run(cmdl, capture_output=True, text=True, env=my_env, cwd=self._runpath,
timeout=self._timeout, check=True)
stdout = cmdres.stdout.strip()
stderr = cmdres.stderr.strip()
returncode = cmdres.returncode
logger.debug("OM output for command %s:\n%s", repr(cmdl), stdout)
if stderr:
raise ModelicaSystemError(f"Error running command {repr(cmdl)}: {stderr}")
except subprocess.TimeoutExpired as ex:
raise ModelicaSystemError(f"Timeout running command {repr(cmdl)}") from ex
except subprocess.CalledProcessError as ex:
raise ModelicaSystemError(f"Error running command {repr(cmdl)}") from ex
return returncode
@staticmethod
def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, str]]]:
"""
Parse a simflag definition; this is deprecated!
The return data can be used as input for self.args_set().
"""
warnings.warn("The argument 'simflags' is depreciated and will be removed in future versions; "
"please use 'simargs' instead", DeprecationWarning, stacklevel=2)
simargs: dict[str, Optional[str | dict[str, str]]] = {}
args = [s for s in simflags.split(' ') if s]
for arg in args:
if arg[0] != '-':
raise ModelicaSystemError(f"Invalid simulation flag: {arg}")
arg = arg[1:]
parts = arg.split('=')
if len(parts) == 1:
simargs[parts[0]] = None
elif parts[0] == 'override':
override = '='.join(parts[1:])
override_dict = {}
for item in override.split(','):
kv = item.split('=')
if not 0 < len(kv) < 3:
raise ModelicaSystemError(f"Invalid value for '-override': {override}")
if kv[0]:
try:
override_dict[kv[0]] = kv[1]
except (KeyError, IndexError) as ex:
raise ModelicaSystemError(f"Invalid value for '-override': {override}") from ex
simargs[parts[0]] = override_dict
return simargs
class ModelicaSystem:
def __init__(
self,
fileName: Optional[str | os.PathLike | pathlib.Path] = None,
modelName: Optional[str] = None,
lmodel: Optional[list[str | tuple[str, str]]] = None,
commandLineOptions: Optional[str] = None,
variableFilter: Optional[str] = None,
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
omhome: Optional[str] = None,
omc_process: Optional[OMCProcessLocal] = None,
build: bool = True,
) -> None:
"""Initialize, load and build a model.
The constructor loads the model file and builds it, generating exe and
xml files, etc.
Args:
fileName: Path to the model file. Either absolute or relative to
the current working directory.
modelName: The name of the model class. If it is contained within
a package, "PackageName.ModelName" should be used.
lmodel: List of libraries to be loaded before the model itself is
loaded. Two formats are supported for the list elements:
lmodel=["Modelica"] for just the library name
and lmodel=[("Modelica","3.2.3")] for specifying both the name
and the version.
commandLineOptions: String with extra command line options to be
provided to omc via setCommandLineOptions().
variableFilter: A regular expression. Only variables fully
matching the regexp will be stored in the result file.
Leaving it unspecified is equivalent to ".*".
customBuildDirectory: Path to a directory to be used for temporary
files like the model executable. If left unspecified, a tmp
directory will be created.
omhome: OPENMODELICAHOME value to be used when creating the OMC
session.
omc_process: definition of a (local) OMC process to be used. If
unspecified, a new local session will be created.
build: Boolean controlling whether or not the model should be
built when constructor is called. If False, the constructor
simply loads the model without compiling.
Examples:
mod = ModelicaSystem("ModelicaModel.mo", "modelName")
mod = ModelicaSystem("ModelicaModel.mo", "modelName", ["Modelica"])
mod = ModelicaSystem("ModelicaModel.mo", "modelName", [("Modelica","3.2.3"), "PowerSystems"])
"""
if fileName is None and modelName is None and not lmodel: # all None
raise ModelicaSystemError("Cannot create ModelicaSystem object without any arguments")
if modelName is None:
raise ModelicaSystemError("A modelname must be provided (argument modelName)!")
self._quantities: list[dict[str, Any]] = []
self._params: dict[str, str] = {} # even numerical values are stored as str
self._inputs: dict[str, list | None] = {}
# _outputs values are str before simulate(), but they can be
# np.float64 after simulate().
self._outputs: dict[str, Any] = {}
# same for _continuous
self._continuous: dict[str, Any] = {}
self._simulate_options: dict[str, str] = {}
self._override_variables: dict[str, str] = {}
self._simulate_options_override: dict[str, str] = {}
self._linearization_options = {'startTime': 0.0, 'stopTime': 1.0, 'stepSize': 0.002, 'tolerance': 1e-8}
self._optimization_options = {'startTime': 0.0, 'stopTime': 1.0, 'numberOfIntervals': 500, 'stepSize': 0.002,
'tolerance': 1e-8}
self._linearized_inputs: list[str] = [] # linearization input list
self._linearized_outputs: list[str] = [] # linearization output list
self._linearized_states: list[str] = [] # linearization states list
if omc_process is not None:
if not isinstance(omc_process, OMCProcessLocal):
raise ModelicaSystemError("Invalid (local) omc process definition provided!")
self._getconn = OMCSessionZMQ(omc_process=omc_process)
else:
self._getconn = OMCSessionZMQ(omhome=omhome)
# set commandLineOptions if provided by users
self.setCommandLineOptions(commandLineOptions=commandLineOptions)
if lmodel is None:
lmodel = []
if not isinstance(lmodel, list):
raise ModelicaSystemError(f"Invalid input type for lmodel: {type(lmodel)} - list expected!")
self._xml_file = None
self._lmodel = lmodel # may be needed if model is derived from other model
self._model_name = modelName # Model class name
self._file_name = pathlib.Path(fileName).resolve() if fileName is not None else None # Model file/package name
self._has_inputs = False # for model with input quantity
self._simulated = False # True if the model has already been simulated
self._result_file: Optional[pathlib.Path] = None # for storing result file
self._variable_filter = variableFilter
if self._file_name is not None and not self._file_name.is_file(): # if file does not exist
raise IOError(f"{self._file_name} does not exist!")
# set default command Line Options for linearization as
# linearize() will use the simulation executable and runtime
# flag -l to perform linearization
self.setCommandLineOptions("--linearizationDumpLanguage=python")
self.setCommandLineOptions("--generateSymbolicLinearization")
self._tempdir = self.setTempDirectory(customBuildDirectory)
if self._file_name is not None:
self._loadLibrary(lmodel=self._lmodel)
self._loadFile(fileName=self._file_name)
# allow directly loading models from MSL without fileName
elif fileName is None and modelName is not None:
self._loadLibrary(lmodel=self._lmodel)
if build:
self.buildModel(variableFilter)
def setCommandLineOptions(self, commandLineOptions: Optional[str] = None):
# set commandLineOptions if provided by users
if commandLineOptions is None:
return
exp = f'setCommandLineOptions("{commandLineOptions}")'
self.sendExpression(exp)
def _loadFile(self, fileName: pathlib.Path):
# load file
self.sendExpression(f'loadFile("{fileName.as_posix()}")')
# for loading file/package, loading model and building model
def _loadLibrary(self, lmodel: list):
# load Modelica standard libraries or Modelica files if needed
for element in lmodel:
if element is not None:
if isinstance(element, str):
if element.endswith(".mo"):
apiCall = "loadFile"
else:
apiCall = "loadModel"
self._requestApi(apiCall, element)
elif isinstance(element, tuple):
if not element[1]:
expr_load_lib = f"loadModel({element[0]})"
else:
expr_load_lib = f'loadModel({element[0]}, {{"{element[1]}"}})'
self.sendExpression(expr_load_lib)
else:
raise ModelicaSystemError("loadLibrary() failed, Unknown type detected: "
f"{element} is of type {type(element)}, "
"The following patterns are supported:\n"
'1)["Modelica"]\n'
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')
def setTempDirectory(self, customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None) -> pathlib.Path:
# create a unique temp directory for each session and build the model in that directory
if customBuildDirectory is not None:
if not os.path.exists(customBuildDirectory):
raise IOError(f"{customBuildDirectory} does not exist")
tempdir = pathlib.Path(customBuildDirectory).absolute()
else:
tempdir = pathlib.Path(tempfile.mkdtemp()).absolute()
if not tempdir.is_dir():
raise IOError(f"{tempdir} could not be created")
logger.info("Define tempdir as %s", tempdir)
exp = f'cd("{tempdir.as_posix()}")'
self.sendExpression(exp)
return tempdir
def getWorkDirectory(self) -> pathlib.Path:
return self._tempdir
def buildModel(self, variableFilter: Optional[str] = None):
if variableFilter is not None:
self._variable_filter = variableFilter
if self._variable_filter is not None:
varFilter = f'variableFilter="{self._variable_filter}"'
else:
varFilter = 'variableFilter=".*"'
buildModelResult = self._requestApi("buildModel", self._model_name, properties=varFilter)
logger.debug("OM model build result: %s", buildModelResult)
self._xml_file = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
self._xmlparse()
def sendExpression(self, expr: str, parsed: bool = True):
try:
retval = self._getconn.sendExpression(expr, parsed)
except OMCSessionException as ex:
raise ModelicaSystemError(f"Error executing {repr(expr)}") from ex
logger.debug(f"Result of executing {repr(expr)}: {textwrap.shorten(repr(retval), width=100)}")
return retval
# request to OMC
def _requestApi(self, apiName, entity=None, properties=None): # 2
if entity is not None and properties is not None:
exp = f'{apiName}({entity}, {properties})'
elif entity is not None and properties is None:
if apiName in ("loadFile", "importFMU"):
exp = f'{apiName}("{entity}")'
else:
exp = f'{apiName}({entity})'
else:
exp = f'{apiName}()'
return self.sendExpression(exp)
def _xmlparse(self):
if not self._xml_file.is_file():
raise ModelicaSystemError(f"XML file not generated: {self._xml_file}")
tree = ET.parse(self._xml_file)
rootCQ = tree.getroot()
for attr in rootCQ.iter('DefaultExperiment'):
for key in ("startTime", "stopTime", "stepSize", "tolerance",
"solver", "outputFormat"):
self._simulate_options[key] = attr.get(key)
for sv in rootCQ.iter('ScalarVariable'):
scalar = {}
for key in ("name", "description", "variability", "causality", "alias"):
scalar[key] = sv.get(key)
scalar["changeable"] = sv.get('isValueChangeable')
scalar["aliasvariable"] = sv.get('aliasVariable')
ch = list(sv)
for att in ch:
scalar["start"] = att.get('start')
scalar["min"] = att.get('min')
scalar["max"] = att.get('max')
scalar["unit"] = att.get('unit')
if scalar["variability"] == "parameter":
if scalar["name"] in self._override_variables:
self._params[scalar["name"]] = self._override_variables[scalar["name"]]
else:
self._params[scalar["name"]] = scalar["start"]
if scalar["variability"] == "continuous":
self._continuous[scalar["name"]] = scalar["start"]
if scalar["causality"] == "input":
self._inputs[scalar["name"]] = scalar["start"]
if scalar["causality"] == "output":
self._outputs[scalar["name"]] = scalar["start"]
self._quantities.append(scalar)
def getQuantities(self, names: Optional[str | list[str]] = None) -> list[dict]:
"""
This method returns list of dictionaries. It displays details of
quantities such as name, value, changeable, and description.
Examples:
>>> mod.getQuantities()
[
{
'alias': 'noAlias',
'aliasvariable': None,
'causality': 'local',
'changeable': 'true',
'description': None,
'max': None,
'min': None,
'name': 'x',
'start': '1.0',
'unit': None,
'variability': 'continuous',
},
{
'name': 'der(x)',
# ...
},
# ...
]
>>> getQuantities("y")
[{
'name': 'y', # ...
}]
>>> getQuantities(["y","x"])
[
{
'name': 'y', # ...
},
{
'name': 'x', # ...
}
]
"""
if names is None:
return self._quantities
if isinstance(names, str):
r = [x for x in self._quantities if x["name"] == names]
if r == []:
raise KeyError(names)
return r
if isinstance(names, list):
return [x for y in names for x in self._quantities if x["name"] == y]
raise ModelicaSystemError("Unhandled input for getQuantities()")
def getContinuous(self, names: Optional[str | list[str]] = None):
"""Get values of continuous signals.
If called before simulate(), the initial values are returned as
strings (or None). If called after simulate(), the final values (at
stopTime) are returned as numpy.float64.
Args:
names: Either None (default), a string with the continuous signal
name, or a list of signal name strings.
Returns:
If `names` is None, a dict in the format
{signal_name: signal_value} is returned.
If `names` is a string, a single element list [signal_value] is
returned.
If `names` is a list, a list with one value for each signal name
in names is returned: [signal1_value, signal2_value, ...].
Examples:
Before simulate():
>>> mod.getContinuous()
{'x': '1.0', 'der(x)': None, 'y': '-0.4'}
>>> mod.getContinuous("y")
['-0.4']
>>> mod.getContinuous(["y","x"])
['-0.4', '1.0']
After simulate():
>>> mod.getContinuous()
{'x': np.float64(0.68), 'der(x)': np.float64(-0.24), 'y': np.float64(-0.24)}
>>> mod.getContinuous("x")
[np.float64(0.68)]
>>> mod.getOutputs(["y","x"])
[np.float64(-0.24), np.float64(0.68)]
"""
if not self._simulated:
if names is None:
return self._continuous
if isinstance(names, str):
return [self._continuous[names]]
if isinstance(names, list):
return [self._continuous[x] for x in names]
else:
if names is None:
for i in self._continuous:
try:
value = self.getSolutions(i)
self._continuous[i] = value[0][-1]
except (OMCSessionException, ModelicaSystemError) as ex:
raise ModelicaSystemError(f"{i} could not be computed") from ex
return self._continuous
if isinstance(names, str):
if names in self._continuous:
value = self.getSolutions(names)
self._continuous[names] = value[0][-1]
return [self._continuous[names]]
else:
raise ModelicaSystemError(f"{names} is not continuous")
if isinstance(names, list):
valuelist = []
for i in names:
if i in self._continuous:
value = self.getSolutions(i)
self._continuous[i] = value[0][-1]
valuelist.append(value[0][-1])
else:
raise ModelicaSystemError(f"{i} is not continuous")
return valuelist
raise ModelicaSystemError("Unhandled input for getContinous()")
def getParameters(self, names: Optional[str | list[str]] = None) -> dict[str, str] | list[str]: # 5
"""Get parameter values.
Args:
names: Either None (default), a string with the parameter name,
or a list of parameter name strings.
Returns:
If `names` is None, a dict in the format
{parameter_name: parameter_value} is returned.
If `names` is a string, a single element list is returned.
If `names` is a list, a list with one value for each parameter name
in names is returned.
In all cases, parameter values are returned as strings.
Examples:
>>> mod.getParameters()
{'Name1': '1.23', 'Name2': '4.56'}
>>> mod.getParameters("Name1")
['1.23']
>>> mod.getParameters(["Name1","Name2"])
['1.23', '4.56']
"""
if names is None:
return self._params
elif isinstance(names, str):
return [self._params[names]]
elif isinstance(names, list):
return [self._params[x] for x in names]
raise ModelicaSystemError("Unhandled input for getParameters()")
def getInputs(self, names: Optional[str | list[str]] = None) -> dict | list: # 6
"""Get values of input signals.
Args:
names: Either None (default), a string with the input name,
or a list of input name strings.
Returns:
If `names` is None, a dict in the format
{input_name: input_value} is returned.
If `names` is a string, a single element list [input_value] is
returned.
If `names` is a list, a list with one value for each input name
in names is returned: [input1_values, input2_values, ...].
In all cases, input values are returned as a list of tuples,
where the first element in the tuple is the time and the second
element is the input value.
Examples:
>>> mod.getInputs()
{'Name1': [(0.0, 0.0), (1.0, 1.0)], 'Name2': None}
>>> mod.getInputs("Name1")
[[(0.0, 0.0), (1.0, 1.0)]]
>>> mod.getInputs(["Name1","Name2"])
[[(0.0, 0.0), (1.0, 1.0)], None]
"""
if names is None:
return self._inputs
elif isinstance(names, str):
return [self._inputs[names]]
elif isinstance(names, list):
return [self._inputs[x] for x in names]
raise ModelicaSystemError("Unhandled input for getInputs()")
def getOutputs(self, names: Optional[str | list[str]] = None): # 7
"""Get values of output signals.
If called before simulate(), the initial values are returned as
strings. If called after simulate(), the final values (at stopTime)
are returned as numpy.float64.
Args:
names: Either None (default), a string with the output name,
or a list of output name strings.
Returns:
If `names` is None, a dict in the format
{output_name: output_value} is returned.
If `names` is a string, a single element list [output_value] is
returned.
If `names` is a list, a list with one value for each output name
in names is returned: [output1_value, output2_value, ...].
Examples:
Before simulate():
>>> mod.getOutputs()
{'out1': '-0.4', 'out2': '1.2'}
>>> mod.getOutputs("out1")
['-0.4']
>>> mod.getOutputs(["out1","out2"])
['-0.4', '1.2']
After simulate():
>>> mod.getOutputs()
{'out1': np.float64(-0.1234), 'out2': np.float64(2.1)}
>>> mod.getOutputs("out1")
[np.float64(-0.1234)]
>>> mod.getOutputs(["out1","out2"])
[np.float64(-0.1234), np.float64(2.1)]
"""
if not self._simulated:
if names is None:
return self._outputs
elif isinstance(names, str):
return [self._outputs[names]]
else:
return [self._outputs[x] for x in names]
else:
if names is None:
for i in self._outputs:
value = self.getSolutions(i)
self._outputs[i] = value[0][-1]
return self._outputs
elif isinstance(names, str):
if names in self._outputs:
value = self.getSolutions(names)
self._outputs[names] = value[0][-1]
return [self._outputs[names]]
else:
raise KeyError(names)
elif isinstance(names, list):
valuelist = []
for i in names:
if i in self._outputs:
value = self.getSolutions(i)
self._outputs[i] = value[0][-1]
valuelist.append(value[0][-1])
else:
raise KeyError(i)
return valuelist
raise ModelicaSystemError("Unhandled input for getOutputs()")
def getSimulationOptions(self, names: Optional[str | list[str]] = None) -> dict[str, str] | list[str]:
"""Get simulation options such as stopTime and tolerance.
Args:
names: Either None (default), a string with the simulation option
name, or a list of option name strings.
Returns:
If `names` is None, a dict in the format
{option_name: option_value} is returned.
If `names` is a string, a single element list [option_value] is
returned.
If `names` is a list, a list with one value for each option name
in names is returned: [option1_value, option2_value, ...].
Option values are always returned as strings.
Examples:
>>> mod.getSimulationOptions()
{'startTime': '0', 'stopTime': '1.234', 'stepSize': '0.002', 'tolerance': '1.1e-08', 'solver': 'dassl', 'outputFormat': 'mat'}
>>> mod.getSimulationOptions("stopTime")
['1.234']
>>> mod.getSimulationOptions(["tolerance", "stopTime"])
['1.1e-08', '1.234']
"""
if names is None:
return self._simulate_options
elif isinstance(names, str):
return [self._simulate_options[names]]
elif isinstance(names, list):
return [self._simulate_options[x] for x in names]
raise ModelicaSystemError("Unhandled input for getSimulationOptions()")
def getLinearizationOptions(self, names: Optional[str | list[str]] = None) -> dict | list:
"""Get simulation options used for linearization.
Args:
names: Either None (default), a string with the linearization option
name, or a list of option name strings.
Returns:
If `names` is None, a dict in the format
{option_name: option_value} is returned.
If `names` is a string, a single element list [option_value] is
returned.
If `names` is a list, a list with one value for each option name
in names is returned: [option1_value, option2_value, ...].
Some option values are returned as float when first initialized,
but always as strings after setLinearizationOptions is used to
change them.
Examples:
>>> mod.getLinearizationOptions()
{'startTime': 0.0, 'stopTime': 1.0, 'stepSize': 0.002, 'tolerance': 1e-08}
>>> mod.getLinearizationOptions("stopTime")
[1.0]
>>> mod.getLinearizationOptions(["tolerance", "stopTime"])
[1e-08, 1.0]
"""
if names is None:
return self._linearization_options
elif isinstance(names, str):
return [self._linearization_options[names]]
elif isinstance(names, list):
return [self._linearization_options[x] for x in names]
raise ModelicaSystemError("Unhandled input for getLinearizationOptions()")
def getOptimizationOptions(self, names: Optional[str | list[str]] = None) -> dict | list:
"""Get simulation options used for optimization.
Args:
names: Either None (default), a string with the optimization option
name, or a list of option name strings.
Returns:
If `names` is None, a dict in the format
{option_name: option_value} is returned.
If `names` is a string, a single element list [option_value] is
returned.
If `names` is a list, a list with one value for each option name
in names is returned: [option1_value, option2_value, ...].
Some option values are returned as float when first initialized,
but always as strings after setOptimizationOptions is used to
change them.
Examples:
>>> mod.getOptimizationOptions()
{'startTime': 0.0, 'stopTime': 1.0, 'numberOfIntervals': 500, 'stepSize': 0.002, 'tolerance': 1e-08}
>>> mod.getOptimizationOptions("stopTime")
[1.0]
>>> mod.getOptimizationOptions(["tolerance", "stopTime"])
[1e-08, 1.0]
"""
if names is None:
return self._optimization_options
elif isinstance(names, str):
return [self._optimization_options[names]]
elif isinstance(names, list):
return [self._optimization_options[x] for x in names]
raise ModelicaSystemError("Unhandled input for getOptimizationOptions()")
def simulate_cmd(
self,
result_file: pathlib.Path,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
timeout: Optional[float] = None,
) -> ModelicaSystemCmd:
"""
This method prepares the simulates model according to the simulation options. It returns an instance of
ModelicaSystemCmd which can be used to run the simulation.
Due to the tempdir being unique for the ModelicaSystem instance, *NEVER* use this to create several simulations
with the same instance of ModelicaSystem! Restart each simulation process with a new instance of ModelicaSystem.
However, if only non-structural parameters are used, it is possible to reuse an existing instance of
ModelicaSystem to create several version ModelicaSystemCmd to run the model using different settings.
Parameters
----------
result_file
simflags
simargs
timeout
Returns
-------
An instance if ModelicaSystemCmd to run the requested simulation.
"""
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
# always define the result file to use
om_cmd.arg_set(key="r", val=result_file.as_posix())
# allow runtime simulation flags from user input
if simflags is not None:
om_cmd.args_set(args=om_cmd.parse_simflags(simflags=simflags))
if simargs:
om_cmd.args_set(args=simargs)
overrideFile = self._tempdir / f"{self._model_name}_override.txt"
if self._override_variables or self._simulate_options_override:
tmpdict = self._override_variables.copy()
tmpdict.update(self._simulate_options_override)
# write to override file
with open(file=overrideFile, mode="w", encoding="utf-8") as fh:
for key, value in tmpdict.items():
fh.write(f"{key}={value}\n")
om_cmd.arg_set(key="overrideFile", val=overrideFile.as_posix())
if self._has_inputs: # if model has input quantities
# csvfile is based on name used for result file
csvfile = result_file.parent / f"{result_file.stem}.csv"
for i in self._inputs:
val = self._inputs[i]
if val is None:
val = [(float(self._simulate_options["startTime"]), 0.0),
(float(self._simulate_options["stopTime"]), 0.0)]
self._inputs[i] = [(float(self._simulate_options["startTime"]), 0.0),
(float(self._simulate_options["stopTime"]), 0.0)]
if float(self._simulate_options["startTime"]) != val[0][0]:
raise ModelicaSystemError(f"startTime not matched for Input {i}!")
if float(self._simulate_options["stopTime"]) != val[-1][0]:
raise ModelicaSystemError(f"stopTime not matched for Input {i}!")
# write csv file and store the name
csvfile = self._createCSVData(csvfile=csvfile)
om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())
return om_cmd
def simulate(
self,
resultfile: Optional[str] = None,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
timeout: Optional[float] = None,
) -> None:
"""Simulate the model according to simulation options.