Skip to content

Commit 1400906

Browse files
authored
Merge branch 'master' into ModelicaSystem_csvfile
2 parents fd3953e + 797eb84 commit 1400906

File tree

1 file changed

+76
-35
lines changed

1 file changed

+76
-35
lines changed

OMPython/ModelicaSystem.py

Lines changed: 76 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
import warnings
5050
import xml.etree.ElementTree as ET
5151

52-
from OMPython.OMCSession import OMCSessionException, OMCSessionZMQ
52+
from OMPython.OMCSession import OMCSessionException, OMCSessionZMQ, OMCProcessLocal
5353

5454
# define logger using the current module name as ID
5555
logger = logging.getLogger(__name__)
@@ -303,7 +303,7 @@ def __init__(
303303
variableFilter: Optional[str] = None,
304304
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
305305
omhome: Optional[str] = None,
306-
session: Optional[OMCSessionZMQ] = None,
306+
omc_process: Optional[OMCProcessLocal] = None,
307307
build: bool = True,
308308
) -> None:
309309
"""Initialize, load and build a model.
@@ -331,8 +331,8 @@ def __init__(
331331
directory will be created.
332332
omhome: OPENMODELICAHOME value to be used when creating the OMC
333333
session.
334-
session: OMC session to be used. If unspecified, a new session
335-
will be created.
334+
omc_process: definition of a (local) OMC process to be used. If
335+
unspecified, a new local session will be created.
336336
build: Boolean controlling whether or not the model should be
337337
built when constructor is called. If False, the constructor
338338
simply loads the model without compiling.
@@ -367,10 +367,10 @@ def __init__(
367367
self._linearized_outputs: list[str] = [] # linearization output list
368368
self._linearized_states: list[str] = [] # linearization states list
369369

370-
if session is not None:
371-
if not isinstance(session, OMCSessionZMQ):
372-
raise ModelicaSystemError("Invalid session data provided!")
373-
self._getconn = session
370+
if omc_process is not None:
371+
if not isinstance(omc_process, OMCProcessLocal):
372+
raise ModelicaSystemError("Invalid (local) omc process definition provided!")
373+
self._getconn = OMCSessionZMQ(omc_process=omc_process)
374374
else:
375375
self._getconn = OMCSessionZMQ(omhome=omhome)
376376

@@ -914,40 +914,39 @@ def getOptimizationOptions(self, names: Optional[str | list[str]] = None) -> dic
914914

915915
raise ModelicaSystemError("Unhandled input for getOptimizationOptions()")
916916

917-
def simulate(self,
918-
resultfile: Optional[str] = None,
919-
simflags: Optional[str] = None,
920-
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
921-
timeout: Optional[float] = None) -> None:
922-
"""Simulate the model according to simulation options.
917+
def simulate_cmd(
918+
self,
919+
resultfile: pathlib.Path,
920+
simflags: Optional[str] = None,
921+
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
922+
timeout: Optional[float] = None,
923+
) -> ModelicaSystemCmd:
924+
"""
925+
This method prepares the simulates model according to the simulation options. It returns an instance of
926+
ModelicaSystemCmd which can be used to run the simulation.
923927
924-
See setSimulationOptions().
928+
Due to the tempdir being unique for the ModelicaSystem instance, *NEVER* use this to create several simulations
929+
with the same instance of ModelicaSystem! Restart each simulation process with a new instance of ModelicaSystem.
925930
926-
Args:
927-
resultfile: Path to a custom result file
928-
simflags: String of extra command line flags for the model binary.
929-
This argument is deprecated, use simargs instead.
930-
simargs: Dict with simulation runtime flags.
931-
timeout: Maximum execution time in seconds.
931+
However, if only non-structural parameters are used, it is possible to reuse an existing instance of
932+
ModelicaSystem to create several version ModelicaSystemCmd to run the model using different settings.
932933
933-
Examples:
934-
mod.simulate()
935-
mod.simulate(resultfile="a.mat")
936-
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10") # set runtime simulation flags, deprecated
937-
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}}) # using simargs
934+
Parameters
935+
----------
936+
resultfile
937+
simflags
938+
simargs
939+
timeout
940+
941+
Returns
942+
-------
943+
An instance if ModelicaSystemCmd to run the requested simulation.
938944
"""
939945

940946
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
941947

942-
if resultfile is None:
943-
# default result file generated by OM
944-
self._result_file = self._tempdir / f"{self._model_name}_res.mat"
945-
elif os.path.exists(resultfile):
946-
self._result_file = pathlib.Path(resultfile)
947-
else:
948-
self._result_file = self._tempdir / resultfile
949-
# always define the resultfile to use
950-
om_cmd.arg_set(key="r", val=self._result_file.as_posix())
948+
# always define the result file to use
949+
om_cmd.arg_set(key="r", val=resultfile.as_posix())
951950

952951
# allow runtime simulation flags from user input
953952
if simflags is not None:
@@ -988,6 +987,48 @@ def simulate(self,
988987

989988
om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())
990989

990+
return om_cmd
991+
992+
def simulate(
993+
self,
994+
resultfile: Optional[str] = None,
995+
simflags: Optional[str] = None,
996+
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
997+
timeout: Optional[float] = None,
998+
) -> None:
999+
"""Simulate the model according to simulation options.
1000+
1001+
See setSimulationOptions().
1002+
1003+
Args:
1004+
resultfile: Path to a custom result file
1005+
simflags: String of extra command line flags for the model binary.
1006+
This argument is deprecated, use simargs instead.
1007+
simargs: Dict with simulation runtime flags.
1008+
timeout: Maximum execution time in seconds.
1009+
1010+
Examples:
1011+
mod.simulate()
1012+
mod.simulate(resultfile="a.mat")
1013+
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10") # set runtime simulation flags, deprecated
1014+
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}}) # using simargs
1015+
"""
1016+
1017+
if resultfile is None:
1018+
# default result file generated by OM
1019+
self._result_file = self._tempdir / f"{self._model_name}_res.mat"
1020+
elif os.path.exists(resultfile):
1021+
self._result_file = pathlib.Path(resultfile)
1022+
else:
1023+
self._result_file = self._tempdir / resultfile
1024+
1025+
om_cmd = self.simulate_cmd(
1026+
resultfile=self._result_file,
1027+
simflags=simflags,
1028+
simargs=simargs,
1029+
timeout=timeout,
1030+
)
1031+
9911032
# delete resultfile ...
9921033
if self._result_file.is_file():
9931034
self._result_file.unlink()

0 commit comments

Comments
 (0)