-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathModelicaSystem.py
More file actions
2683 lines (2245 loc) · 104 KB
/
ModelicaSystem.py
File metadata and controls
2683 lines (2245 loc) · 104 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.
"""
import abc
import ast
from dataclasses import dataclass
import itertools
import logging
import numbers
import os
import pathlib
import queue
import re
import textwrap
import threading
from typing import Any, cast, Optional, Tuple
import warnings
import xml.etree.ElementTree as ET
import numpy as np
from OMPython.OMCSession import (
ModelExecutionData,
ModelExecutionException,
OMCSessionException,
OMCSessionLocal,
OMPathABC,
OMSessionABC,
OMSessionRunner,
)
# define logger using the current module name as ID
logger = logging.getLogger(__name__)
class ModelicaSystemError(Exception):
"""
Exception used in ModelicaSystem 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 ModelExecutionCmd:
"""
All information about a compiled model executable. This should include data about all structured parameters, i.e.
parameters which need a recompilation of the model. All non-structured parameters can be easily changed without
the need for recompilation.
"""
def __init__(
self,
runpath: os.PathLike,
cmd_prefix: list[str],
cmd_local: bool = False,
cmd_windows: bool = False,
timeout: float = 10.0,
model_name: Optional[str] = None,
) -> None:
if model_name is None:
raise ModelExecutionException("Missing model name!")
self._cmd_local = cmd_local
self._cmd_windows = cmd_windows
self._cmd_prefix = cmd_prefix
self._runpath = pathlib.PurePosixPath(runpath)
self._model_name = model_name
self._timeout = timeout
# dictionaries of command line arguments for the model executable
self._args: dict[str, str | None] = {}
# 'override' argument needs special handling, as it is a dict on its own saved as dict elements following the
# structure: 'key' => 'key=value'
self._arg_override: dict[str, str] = {}
def arg_set(
self,
key: str,
val: Optional[str | dict[str, Any] | numbers.Number] = None,
) -> None:
"""
Set one argument for the executable model.
Args:
key: identifier / argument name to be used for the call of the model executable.
val: value for the given key; None for no value and for key == 'override' a dictionary can be used which
indicates variables to override
"""
def override2str(
orkey: str,
orval: str | bool | numbers.Number,
) -> str:
"""
Convert a value for 'override' to a string taking into account differences between Modelica and Python.
"""
# check oval for any string representations of numbers (or bool) and convert these to Python representations
if isinstance(orval, str):
try:
val_evaluated = ast.literal_eval(orval)
if isinstance(val_evaluated, (numbers.Number, bool)):
orval = val_evaluated
except (ValueError, SyntaxError):
pass
if isinstance(orval, str):
val_str = orval.strip()
elif isinstance(orval, bool):
val_str = 'true' if orval else 'false'
elif isinstance(orval, numbers.Number):
val_str = str(orval)
else:
raise ModelExecutionException(f"Invalid value for override key {orkey}: {type(orval)}")
return f"{orkey}={val_str}"
if not isinstance(key, str):
raise ModelExecutionException(f"Invalid argument key: {repr(key)} (type: {type(key)})")
key = key.strip()
if isinstance(val, dict):
if key != 'override':
raise ModelExecutionException("Dictionary input only possible for key 'override'!")
for okey, oval in val.items():
if not isinstance(okey, str):
raise ModelExecutionException("Invalid key for argument 'override': "
f"{repr(okey)} (type: {type(okey)})")
if not isinstance(oval, (str, bool, numbers.Number, type(None))):
raise ModelExecutionException(f"Invalid input for 'override'.{repr(okey)}: "
f"{repr(oval)} (type: {type(oval)})")
if okey in self._arg_override:
if oval is None:
logger.info(f"Remove model executable override argument: {repr(self._arg_override[okey])}")
del self._arg_override[okey]
continue
logger.info(f"Update model executable override argument: {repr(okey)} = {repr(oval)} "
f"(was: {repr(self._arg_override[okey])})")
if oval is not None:
self._arg_override[okey] = override2str(orkey=okey, orval=oval)
argval = ','.join(sorted(self._arg_override.values()))
elif val is None:
argval = None
elif isinstance(val, str):
argval = val.strip()
elif isinstance(val, numbers.Number):
argval = str(val)
else:
raise ModelExecutionException(f"Invalid argument value for {repr(key)}: {repr(val)} (type: {type(val)})")
if key in self._args:
logger.warning(f"Override 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[str, str | bool | numbers.Number]]:
"""
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, Any] | numbers.Number]],
) -> None:
"""
Define arguments for the model executable.
"""
for arg in args:
self.arg_set(key=arg, val=args[arg])
def get_cmd_args(self) -> list[str]:
"""
Get a list with the command arguments for the model executable.
"""
cmdl = []
for key in sorted(self._args):
if self._args[key] is None:
cmdl.append(f"-{key}")
else:
cmdl.append(f"-{key}={self._args[key]}")
return cmdl
def definition(self) -> ModelExecutionData:
"""
Define all needed data to run the model executable. The data is stored in an OMCSessionRunData object.
"""
# ensure that a result filename is provided
result_file = self.arg_get('r')
if not isinstance(result_file, str):
result_file = (self._runpath / f"{self._model_name}.mat").as_posix()
# as this is the local implementation, pathlib.Path can be used
cmd_path = self._runpath
cmd_library_path = None
if self._cmd_local and self._cmd_windows:
cmd_library_path = ""
# set the process environment from the generated .bat file in windows which should have all the dependencies
# for this pathlib.PurePosixPath() must be converted to a pathlib.Path() object, i.e. WindowsPath
path_bat = pathlib.Path(cmd_path) / f"{self._model_name}.bat"
if not path_bat.is_file():
raise ModelExecutionException("Batch file (*.bat) does not exist " + str(path_bat))
content = path_bat.read_text(encoding='utf-8')
for line in content.splitlines():
match = re.match(pattern=r"^SET PATH=([^%]*)", string=line, flags=re.IGNORECASE)
if match:
cmd_library_path = match.group(1).strip(';') # Remove any trailing semicolons
my_env = os.environ.copy()
my_env["PATH"] = cmd_library_path + os.pathsep + my_env["PATH"]
cmd_model_executable = cmd_path / f"{self._model_name}.exe"
else:
# for Linux the paths to the needed libraries should be included in the executable (using rpath)
cmd_model_executable = cmd_path / self._model_name
# define local(!) working directory
cmd_cwd_local = None
if self._cmd_local:
cmd_cwd_local = cmd_path.as_posix()
omc_run_data = ModelExecutionData(
cmd_path=cmd_path.as_posix(),
cmd_model_name=self._model_name,
cmd_args=self.get_cmd_args(),
cmd_result_file=result_file,
cmd_prefix=self._cmd_prefix,
cmd_library_path=cmd_library_path,
cmd_model_executable=cmd_model_executable.as_posix(),
cmd_cwd_local=cmd_cwd_local,
cmd_timeout=self._timeout,
)
return omc_run_data
@staticmethod
def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, Any] | numbers.Number]]:
"""
Parse a simflag definition; this is deprecated!
The return data can be used as input for self.args_set().
"""
warnings.warn(
message="The argument 'simflags' is depreciated and will be removed in future versions; "
"please use 'simargs' instead",
category=DeprecationWarning,
stacklevel=2,
)
simargs: dict[str, Optional[str | dict[str, Any] | numbers.Number]] = {}
args = [s for s in simflags.split(' ') if s]
for arg in args:
if arg[0] != '-':
raise ModelExecutionException(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 ModelExecutionException(f"Invalid value for '-override': {override}")
if kv[0]:
try:
override_dict[kv[0]] = kv[1]
except (KeyError, IndexError) as ex:
raise ModelExecutionException(f"Invalid value for '-override': {override}") from ex
simargs[parts[0]] = override_dict
return simargs
class ModelicaSystemABC(metaclass=abc.ABCMeta):
"""
Base class to simulate a Modelica models.
"""
def __init__(
self,
session: OMSessionABC,
work_directory: Optional[str | os.PathLike] = None,
) -> None:
"""Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo().
Args:
work_directory: Path to a directory to be used for temporary
files like the model executable. If left unspecified, a tmp
directory will be created.
session: definition of a (local) OMC session to be used. If
unspecified, a new local session will be created.
"""
self._quantities: list[dict[str, Any]] = []
self._params: dict[str, str] = {} # even numerical values are stored as str
self._inputs: dict[str, list[tuple[float, float]]] = {}
self._outputs: dict[str, np.float64] = {} # numpy.float64 as it allows to define None values
self._continuous: dict[str, np.float64] = {} # numpy.float64 as it allows to define None values
self._simulate_options: dict[str, str] = {}
self._override_variables: dict[str, str] = {}
self._simulate_options_override: dict[str, str] = {}
self._linearization_options: dict[str, str] = {
'startTime': str(0.0),
'stopTime': str(1.0),
'stepSize': str(0.002),
'tolerance': str(1e-8),
}
self._optimization_options = self._linearization_options | {
'numberOfIntervals': str(500),
}
self._linearized_inputs: list[str] = [] # linearization input list
self._linearized_outputs: list[str] = [] # linearization output list
self._linearized_states: list[str] = [] # linearization states list
self._session = session
# get OpenModelica version
version_str = self._session.get_version()
self._version = self._parse_om_version(version=version_str)
self._simulated = False # True if the model has already been simulated
self._result_file: Optional[OMPathABC] = None # for storing result file
self._work_dir: OMPathABC = self.setWorkDirectory(work_directory)
self._model_name: Optional[str] = None
self._libraries: Optional[list[str | tuple[str, str]]] = None
self._file_name: Optional[OMPathABC] = None
self._variable_filter: Optional[str] = None
def get_session(self) -> OMSessionABC:
"""
Return the OMC session used for this class.
"""
return self._session
def get_model_name(self) -> str:
"""
Return the defined model name.
"""
if not isinstance(self._model_name, str):
raise ModelicaSystemError("No model name defined!")
return self._model_name
def setWorkDirectory(self, work_directory: Optional[str | os.PathLike] = None) -> OMPathABC:
"""
Define the work directory for the ModelicaSystem / OpenModelica session. The model is build within this
directory. If no directory is defined a unique temporary directory is created.
"""
if work_directory is not None:
workdir = self._session.omcpath(work_directory).absolute()
if not workdir.is_dir():
raise IOError(f"Provided work directory does not exists: {work_directory}!")
else:
workdir = self._session.omcpath_tempdir().absolute()
if not workdir.is_dir():
raise IOError(f"{workdir} could not be created")
logger.info("Define work dir as %s", workdir)
self._session.set_workdir(workdir=workdir)
# set the class variable _work_dir ...
self._work_dir = workdir
# ... and also return the defined path
return workdir
def getWorkDirectory(self) -> OMPathABC:
"""
Return the defined working directory for this ModelicaSystem / OpenModelica session.
"""
return self._work_dir
def check_model_executable(self):
"""
Check if the model executable is working
"""
# check if the executable exists ...
om_cmd = ModelExecutionCmd(
runpath=self.getWorkDirectory(),
cmd_local=self._session.model_execution_local,
cmd_windows=self._session.model_execution_windows,
cmd_prefix=self._session.model_execution_prefix(cwd=self.getWorkDirectory()),
model_name=self._model_name,
)
# ... by running it - output help for command help
om_cmd.arg_set(key="help", val="help")
cmd_definition = om_cmd.definition()
returncode = cmd_definition.run()
if returncode != 0:
raise ModelicaSystemError("Model executable not working!")
def _xmlparse(self, xml_file: OMPathABC):
if not xml_file.is_file():
raise ModelicaSystemError(f"XML file not generated: {xml_file}")
xml_content = xml_file.read_text()
tree = ET.ElementTree(ET.fromstring(xml_content))
root = tree.getroot()
for attr in root.iter('DefaultExperiment'):
for key in ("startTime", "stopTime", "stepSize", "tolerance",
"solver", "outputFormat"):
self._simulate_options[key] = str(attr.get(key))
for sv in root.iter('ScalarVariable'):
translations = {
"alias": "alias",
"aliasvariable": "aliasVariable",
"causality": "causality",
"changeable": "isValueChangeable",
"description": "description",
"name": "name",
"variability": "variability",
}
scalar: dict[str, Any] = {}
for key_dst, key_src in translations.items():
val = sv.get(key_src)
scalar[key_dst] = None if val is None else str(val)
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')
# save parameters in the corresponding class variables
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"]] = np.float64(scalar["start"])
if scalar["causality"] == "input":
self._inputs[scalar["name"]] = scalar["start"]
if scalar["causality"] == "output":
self._outputs[scalar["name"]] = np.float64(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 getContinuousInitial(
self,
names: Optional[str | list[str]] = None,
) -> dict[str, np.float64] | list[np.float64]:
"""
Get (initial) values of continuous signals.
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:
>>> mod.getContinuousInitial()
{'x': '1.0', 'der(x)': None, 'y': '-0.4'}
>>> mod.getContinuousInitial("y")
['-0.4']
>>> mod.getContinuousInitial(["y","x"])
['-0.4', '1.0']
"""
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]
raise ModelicaSystemError("Unhandled input for getContinousInitial()")
def getParameters(
self,
names: Optional[str | list[str]] = None,
) -> dict[str, str] | list[str]:
"""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
if isinstance(names, str):
return [self._params[names]]
if 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[str, list[tuple[float, float]]] | list[list[tuple[float, float]]]:
"""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
if isinstance(names, str):
return [self._inputs[names]]
if isinstance(names, list):
return [self._inputs[x] for x in names]
raise ModelicaSystemError("Unhandled input for getInputs()")
def getOutputsInitial(
self,
names: Optional[str | list[str]] = None,
) -> dict[str, np.float64] | list[np.float64]:
"""
Get (initial) values of output signals.
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:
>>> mod.getOutputsInitial()
{'out1': '-0.4', 'out2': '1.2'}
>>> mod.getOutputsInitial("out1")
['-0.4']
>>> mod.getOutputsInitial(["out1","out2"])
['-0.4', '1.2']
"""
if names is None:
return self._outputs
if isinstance(names, str):
return [self._outputs[names]]
if isinstance(names, list):
return [self._outputs[x] for x in names]
raise ModelicaSystemError("Unhandled input for getOutputsInitial()")
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
if isinstance(names, str):
return [self._simulate_options[names]]
if 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[str, str] | list[str]:
"""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, ...].
The option values are always returned as strings.
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
if isinstance(names, str):
return [self._linearization_options[names]]
if 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[str, str] | list[str]:
"""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, ...].
The option values are always returned as string.
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
if isinstance(names, str):
return [self._optimization_options[names]]
if isinstance(names, list):
return [self._optimization_options[x] for x in names]
raise ModelicaSystemError("Unhandled input for getOptimizationOptions()")
@staticmethod
def _parse_om_version(version: str) -> tuple[int, int, int]:
"""
Evaluate an OMC version string and return a tuple of (epoch, major, minor).
"""
match = re.search(pattern=r"v?(\d+)\.(\d+)\.(\d+)", string=version)
if not match:
raise ValueError(f"Version not found in: {version}")
major, minor, patch = map(int, match.groups())
return major, minor, patch
def _process_override_data(
self,
om_cmd: ModelExecutionCmd,
override_file: OMPathABC,
override_var: dict[str, str],
override_sim: dict[str, str],
) -> None:
"""
Define the override parameters. As the definition of simulation specific override parameter changes with OM
1.26.0, version specific code is needed. Please keep in mind, that this will fail if OMC is not used to run the
model executable.
"""
if len(override_var) == 0 and len(override_sim) == 0:
return
override_content = ""
if override_var:
override_content += "\n".join([f"{key}={value}" for key, value in override_var.items()]) + "\n"
# simulation options are not read from override file from version >= 1.26.0,
# pass them to simulation executable directly as individual arguments
# see https://github.com/OpenModelica/OpenModelica/pull/14813
if override_sim:
if self._version >= (1, 26, 0):
for key, opt_value in override_sim.items():
om_cmd.arg_set(key=key, val=str(opt_value))
else:
override_content += "\n".join([f"{key}={value}" for key, value in override_sim.items()]) + "\n"
if override_content:
override_file.write_text(override_content)
om_cmd.arg_set(key="overrideFile", val=override_file.as_posix())
def simulate_cmd(
self,
result_file: OMPathABC,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> ModelExecutionCmd:
"""
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
Returns
-------
An instance if ModelicaSystemCmd to run the requested simulation.
"""
om_cmd = ModelExecutionCmd(
runpath=self.getWorkDirectory(),
cmd_local=self._session.model_execution_local,
cmd_windows=self._session.model_execution_windows,
cmd_prefix=self._session.model_execution_prefix(cwd=self.getWorkDirectory()),
model_name=self._model_name,
)
# 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)
self._process_override_data(
om_cmd=om_cmd,
override_file=result_file.parent / f"{result_file.stem}_override.txt",
override_var=self._override_variables,
override_sim=self._simulate_options_override,
)
if self._inputs: # if model has input quantities
for key, val in self._inputs.items():
if val is None:
val = [(float(self._simulate_options["startTime"]), 0.0),
(float(self._simulate_options["stopTime"]), 0.0)]
self._inputs[key] = val
if float(self._simulate_options["startTime"]) != val[0][0]:
raise ModelicaSystemError(f"startTime not matched for Input {key}!")
if float(self._simulate_options["stopTime"]) != val[-1][0]:
raise ModelicaSystemError(f"stopTime not matched for Input {key}!")
# csvfile is based on name used for result file
csvfile = result_file.parent / f"{result_file.stem}.csv"
# 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 | os.PathLike] = None,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> None:
"""Simulate the model according to simulation options.
See setSimulationOptions().
Args:
resultfile: Path to a custom result file
simflags: String of extra command line flags for the model binary.
This argument is deprecated, use simargs instead.
simargs: Dict with simulation runtime flags.
Examples:
mod.simulate()
mod.simulate(resultfile="a.mat")
# set runtime simulation flags, deprecated
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10")
# using simargs
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}})
"""
if resultfile is None:
# default result file generated by OM
self._result_file = self.getWorkDirectory() / f"{self._model_name}_res.mat"
elif isinstance(resultfile, OMPathABC):
self._result_file = resultfile
else:
self._result_file = self._session.omcpath(resultfile)
if not self._result_file.is_absolute():
self._result_file = self.getWorkDirectory() / resultfile
if not isinstance(self._result_file, OMPathABC):
raise ModelicaSystemError(f"Invalid result file path: {self._result_file} - must be an OMCPath object!")
om_cmd = self.simulate_cmd(
result_file=self._result_file,
simflags=simflags,
simargs=simargs,
)
# delete resultfile ...
if self._result_file.is_file():
self._result_file.unlink()
# ... run simulation ...
cmd_definition = om_cmd.definition()
returncode = cmd_definition.run()
# and check returncode *AND* resultfile
if returncode != 0 and self._result_file.is_file():
# check for an empty (=> 0B) result file which indicates a crash of the model executable
# see: https://github.com/OpenModelica/OMPython/issues/261
# https://github.com/OpenModelica/OpenModelica/issues/13829
if self._result_file.size() == 0:
self._result_file.unlink()
raise ModelicaSystemError("Empty result file - this indicates a crash of the model executable!")
logger.warning(f"Return code = {returncode} but result file exists!")