-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathModelicaSystem.py
More file actions
2230 lines (1873 loc) · 87.6 KB
/
ModelicaSystem.py
File metadata and controls
2230 lines (1873 loc) · 87.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.
"""
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
import warnings
import xml.etree.ElementTree as ET
import numpy as np
from OMPython.OMCSession import (
OMCSessionException,
OMCSessionRunData,
OMCSession,
OMCSessionLocal,
OMCPath,
)
# 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:
"""
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,
session: OMCSession,
runpath: OMCPath,
modelname: Optional[str] = None,
) -> None:
if modelname is None:
raise ModelicaSystemError("Missing model name!")
self._session = session
self._runpath = runpath
self._model_name = modelname
# 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(
okey: str,
oval: 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(oval, str):
try:
oval_evaluated = ast.literal_eval(oval)
if isinstance(oval_evaluated, (numbers.Number, bool)):
oval = oval_evaluated
except (ValueError, SyntaxError):
pass
if isinstance(oval, str):
oval_str = oval.strip()
elif isinstance(oval, bool):
oval_str = 'true' if oval else 'false'
elif isinstance(oval, numbers.Number):
oval_str = str(oval)
else:
raise ModelicaSystemError(f"Invalid value for override key {okey}: {type(oval)}")
return f"{okey}={oval_str}"
if not isinstance(key, str):
raise ModelicaSystemError(f"Invalid argument key: {repr(key)} (type: {type(key)})")
key = key.strip()
if isinstance(val, dict):
if key != 'override':
raise ModelicaSystemError("Dictionary input only possible for key 'override'!")
for okey, oval in val.items():
if not isinstance(okey, str):
raise ModelicaSystemError("Invalid key for argument 'override': "
f"{repr(okey)} (type: {type(okey)})")
if not isinstance(oval, (str, bool, numbers.Number, type(None))):
raise ModelicaSystemError(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(okey=okey, oval=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 ModelicaSystemError(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) -> OMCSessionRunData:
"""
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()
omc_run_data = OMCSessionRunData(
cmd_path=self._runpath.as_posix(),
cmd_model_name=self._model_name,
cmd_args=self.get_cmd_args(),
cmd_result_path=result_file,
)
omc_run_data_updated = self._session.omc_run_data_update(
omc_run_data=omc_run_data,
)
return omc_run_data_updated
class ModelicaSystem:
"""
Class to simulate a Modelica model using OpenModelica via OMCSession.
"""
def __init__(
self,
command_line_options: Optional[list[str]] = None,
work_directory: Optional[str | os.PathLike] = None,
omhome: Optional[str] = None,
session: Optional[OMCSession] = None,
) -> None:
"""Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo().
Args:
command_line_options: List with extra command line options as elements. The list elements are
provided to omc via setCommandLineOptions(). If set, the default values will be overridden.
To disable any command line options, use an empty list.
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.
omhome: path to OMC to be used when creating the OMC session (see OMCSession).
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]]] = {}
# _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: 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
if session is not None:
self._session = session
else:
self._session = OMCSessionLocal(omhome=omhome)
# get OpenModelica version
version_str = self.sendExpression(expr="getVersion()")
self._version = self._parse_om_version(version=version_str)
# set commandLineOptions using default values or the user defined list
if command_line_options is None:
# set default command line options to improve the performance of linearization and to avoid recompilation if
# the simulation executable is reused in linearize() via the runtime flag '-l'
command_line_options = [
"--linearizationDumpLanguage=python",
"--generateSymbolicLinearization",
]
for opt in command_line_options:
self.set_command_line_options(command_line_option=opt)
self._simulated = False # True if the model has already been simulated
self._result_file: Optional[OMCPath] = None # for storing result file
self._work_dir: OMCPath = self.setWorkDirectory(work_directory)
self._model_name: Optional[str] = None
self._libraries: Optional[list[str | tuple[str, str]]] = None
self._file_name: Optional[OMCPath] = None
self._variable_filter: Optional[str] = None
def model(
self,
model_name: Optional[str] = None,
model_file: Optional[str | os.PathLike] = None,
libraries: Optional[list[str | tuple[str, str]]] = None,
variable_filter: Optional[str] = None,
build: bool = True,
) -> None:
"""Load and build a Modelica model.
This method loads the model file and builds it if requested (build == True).
Args:
model_file: Path to the model file. Either absolute or relative to
the current working directory.
model_name: The name of the model class. If it is contained within
a package, "PackageName.ModelName" should be used.
libraries: 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.
variable_filter: A regular expression. Only variables fully
matching the regexp will be stored in the result file.
Leaving it unspecified is equivalent to ".*".
build: Boolean controlling whether the model should be
built when constructor is called. If False, the constructor
simply loads the model without compiling.
Examples:
mod = ModelicaSystem()
# and then one of the lines below
mod.model(name="modelName", file="ModelicaModel.mo", )
mod.model(name="modelName", file="ModelicaModel.mo", libraries=["Modelica"])
mod.model(name="modelName", file="ModelicaModel.mo", libraries=[("Modelica","3.2.3"), "PowerSystems"])
"""
if self._model_name is not None:
raise ModelicaSystemError("Can not reuse this instance of ModelicaSystem "
f"defined for {repr(self._model_name)}!")
if model_name is None or not isinstance(model_name, str):
raise ModelicaSystemError("A model name must be provided!")
if libraries is None:
libraries = []
if not isinstance(libraries, list):
raise ModelicaSystemError(f"Invalid input type for libraries: {type(libraries)} - list expected!")
# set variables
self._model_name = model_name # Model class name
self._libraries = libraries # may be needed if model is derived from other model
self._variable_filter = variable_filter
if self._libraries:
self._loadLibrary(libraries=self._libraries)
self._file_name = None
if model_file is not None:
file_path = pathlib.Path(model_file)
# special handling for OMCProcessLocal - consider a relative path
if isinstance(self._session, OMCSessionLocal) and not file_path.is_absolute():
file_path = pathlib.Path.cwd() / file_path
if not file_path.is_file():
raise IOError(f"Model file {file_path} does not exist!")
self._file_name = self.getWorkDirectory() / file_path.name
if (isinstance(self._session, OMCSessionLocal)
and file_path.as_posix() == self._file_name.as_posix()):
pass
elif self._file_name.is_file():
raise IOError(f"Simulation model file {self._file_name} exist - not overwriting!")
else:
content = file_path.read_text(encoding='utf-8')
self._file_name.write_text(content)
if self._file_name is not None:
self._loadFile(fileName=self._file_name)
if build:
self.buildModel(variable_filter)
def get_session(self) -> OMCSession:
"""
Return the OMC session used for this class.
"""
return self._session
def set_command_line_options(self, command_line_option: str):
"""
Set the provided command line option via OMC setCommandLineOptions().
"""
exp = f'setCommandLineOptions("{command_line_option}")'
self.sendExpression(exp)
def _loadFile(self, fileName: OMCPath):
# load file
self.sendExpression(f'loadFile("{fileName.as_posix()}")')
# for loading file/package, loading model and building model
def _loadLibrary(self, libraries: list):
# load Modelica standard libraries or Modelica files if needed
for element in libraries:
if element is not None:
if isinstance(element, str):
if element.endswith(".mo"):
api_call = "loadFile"
else:
api_call = "loadModel"
self._requestApi(apiName=api_call, entity=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 setWorkDirectory(self, work_directory: Optional[str | os.PathLike] = None) -> OMCPath:
"""
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)
exp = f'cd("{workdir.as_posix()}")'
self.sendExpression(exp)
# set the class variable _work_dir ...
self._work_dir = workdir
# ... and also return the defined path
return workdir
def getWorkDirectory(self) -> OMCPath:
"""
Return the defined working directory for this ModelicaSystem / OpenModelica session.
"""
return self._work_dir
def buildModel(self, variableFilter: Optional[str] = None):
filter_def: Optional[str] = None
if variableFilter is not None:
filter_def = variableFilter
elif self._variable_filter is not None:
filter_def = self._variable_filter
if filter_def is not None:
var_filter = f'variableFilter="{filter_def}"'
else:
var_filter = 'variableFilter=".*"'
build_model_result = self._requestApi(apiName="buildModel", entity=self._model_name, properties=var_filter)
logger.debug("OM model build result: %s", build_model_result)
# check if the executable exists ...
om_cmd = ModelicaSystemCmd(
session=self._session,
runpath=self.getWorkDirectory(),
modelname=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 = self._session.run_model_executable(cmd_run_data=cmd_definition)
if returncode != 0:
raise ModelicaSystemError("Model executable not working!")
xml_file = self._session.omcpath(build_model_result[0]).parent / build_model_result[1]
self._xmlparse(xml_file=xml_file)
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
try:
retval = self._session.sendExpression(command=expr, parsed=parsed)
except OMCSessionException as ex:
raise ModelicaSystemError(f"Error executing {repr(expr)}: {ex}") 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: str,
entity: Optional[str] = None,
properties: Optional[str] = None,
) -> Any:
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, xml_file: OMCPath):
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"]] = 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,
) -> dict[str, str | numbers.Real] | list[str | numbers.Real]:
"""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]
if names is None:
for name in self._continuous:
try:
value = self.getSolutions(name)
self._continuous[name] = value[0][-1]
except (OMCSessionException, ModelicaSystemError) as ex:
raise ModelicaSystemError(f"{name} 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]]
raise ModelicaSystemError(f"{names} is not continuous")
if isinstance(names, list):
valuelist = []
for name in names:
if name in self._continuous:
value = self.getSolutions(name)
self._continuous[name] = value[0][-1]
valuelist.append(value[0][-1])
else:
raise ModelicaSystemError(f"{name} 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]:
"""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 getOutputs(
self,
names: Optional[str | list[str]] = None,
) -> dict[str, str | numbers.Real] | list[str | numbers.Real]:
"""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
if isinstance(names, str):
return [self._outputs[names]]
return [self._outputs[x] for x in names]
if names is None:
for name in self._outputs:
value = self.getSolutions(name)
self._outputs[name] = value[0][-1]
return self._outputs
if isinstance(names, str):
if names in self._outputs:
value = self.getSolutions(names)
self._outputs[names] = value[0][-1]
return [self._outputs[names]]
raise KeyError(names)
if isinstance(names, list):
valuelist = []
for name in names:
if name in self._outputs:
value = self.getSolutions(name)
self._outputs[name] = value[0][-1]
valuelist.append(value[0][-1])
else:
raise KeyError(name)
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
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()")
def _parse_om_version(self, version: str) -> tuple[int, int, int]:
match = re.search(r"v?(\d+)\.(\d+)\.(\d+)", 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: ModelicaSystemCmd,
override_file: OMCPath,
override_var: dict[str, str],
override_sim: dict[str, str],
) -> None: