Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 116 additions & 33 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"""

import logging
import numbers
import os
import pathlib
import platform
from typing import Any, Optional
import warnings

Expand All @@ -16,10 +16,14 @@
ModelExecutionConfig,
ModelExecutionException,
)
from OMPython.om_session_abc import (
OMPathABC,
)
from OMPython.om_session_omc import (
OMCSessionLocal,
)
from OMPython.modelica_system_abc import (
LinearizationResult,
ModelicaSystemError,
)
from OMPython.modelica_system_omc import (
Expand Down Expand Up @@ -73,8 +77,73 @@ def __init__(
def setCommandLineOptions(self, commandLineOptions: str):
super().set_command_line_options(command_line_option=commandLineOptions)

def _set_compatibility_helper(
def simulate_cmd( # type: ignore[override]
self,
result_file: OMPathABC,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> ModelExecutionConfig:
"""
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
"""

if simargs is None:
simargs = {}

if simflags is not None:
simargs_extra = parse_simflags(simflags=simflags)
simargs = simargs | simargs_extra

return super().simulate_cmd(
result_file=result_file,
simargs=simargs,
)

def simulate( # type: ignore[override]
self,
resultfile: Optional[str | os.PathLike] = None,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> None:
"""
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
"""

if simargs is None:
simargs = {}

if simflags is not None:
simargs_extra = parse_simflags(simflags=simflags)
simargs = simargs | simargs_extra

return super().simulate(
resultfile=resultfile,
simargs=simargs,
)

def linearize( # type: ignore[override]
self,
lintime: Optional[float] = None,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> LinearizationResult:
"""
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
"""
if simargs is None:
simargs = {}

if simflags is not None:
simargs_extra = parse_simflags(simflags=simflags)
simargs = simargs | simargs_extra

return super().linearize(
lintime=lintime,
simargs=simargs,
)

@staticmethod
def _set_compatibility_helper(
pkey: str,
args: Any,
kwargs: dict[str, Any],
Expand Down Expand Up @@ -330,7 +399,12 @@ class ModelicaSystemDoE(ModelicaDoEOMC):
@depreciated_class(msg="Please use class ModelExecutionConfig instead!")
class ModelicaSystemCmd(ModelExecutionConfig):
"""
Compatibility class; in the new version it is renamed as ModelExecutionConfig.
Compatibility class; not much content.

Missing definitions:
* get_exe() - see self.definition.cmd_model_executable
* get_cmd() - use self.get_cmd_args() or self.definition().get_cmd()
* run() - use self.definition().run()
"""

def __init__(
Expand All @@ -346,35 +420,44 @@ def __init__(
model_name=modelname,
)

def get_exe(self) -> pathlib.Path:
"""Get the path to the compiled model executable."""

path_run = pathlib.Path(self._runpath)
if platform.system() == "Windows":
path_exe = path_run / f"{self._model_name}.exe"
else:
path_exe = path_run / 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().
"""

cmdl = [self.get_exe().as_posix()] + self.get_cmd_args()

return cmdl
def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, Any] | numbers.Number]]:
"""
Parse a simflag definition; this is deprecated!

def run(self) -> int:
cmd_definition = self.definition()
try:
returncode = cmd_definition.run()
except ModelExecutionException as exc:
raise ModelicaSystemError(f"Cannot execute model: {exc}") from exc
return returncode
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
9 changes: 8 additions & 1 deletion OMPython/OMCSession.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import logging
from typing import Any, Optional
import warnings

import pyparsing

Expand Down Expand Up @@ -272,7 +273,13 @@ def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC
return self.omc_process.omcpath_tempdir(tempdir_base=tempdir_base)

def execute(self, command: str):
return self.omc_process.execute(command=command)
warnings.warn(
message="This function is depreciated and will be removed in future versions; "
"please use sendExpression() instead",
category=DeprecationWarning,
stacklevel=2,
)
return self.omc_process.sendExpression(expr=command, parsed=False)

def sendExpression(
self,
Expand Down
4 changes: 2 additions & 2 deletions OMPython/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@
# the imports below are compatibility functionality (OMPython v4.0.0)
from OMPython.ModelicaSystem import (
ModelicaSystem,
ModelicaSystemCmd,
ModelicaSystemDoE,
parse_simflags,
)
from OMPython.OMCSession import (
OMCSessionCmd,
Expand Down Expand Up @@ -109,9 +109,9 @@
'OMPathRunnerLocal',
'OMSessionRunner',

'ModelicaSystemCmd',
'ModelicaSystem',
'ModelicaSystemDoE',
'parse_simflags',

'OMCSessionCmd',

Expand Down
43 changes: 0 additions & 43 deletions OMPython/model_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import re
import subprocess
from typing import Any, Optional
import warnings

# define logger using the current module name as ID
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -314,45 +313,3 @@ def definition(self) -> ModelExecutionRun:
)

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
20 changes: 0 additions & 20 deletions OMPython/modelica_system_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,6 @@ def _process_override_data(
def simulate_cmd(
self,
result_file: OMPathABC,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> ModelExecutionConfig:
"""
Expand All @@ -636,7 +635,6 @@ def simulate_cmd(
Parameters
----------
result_file
simflags
simargs

Returns
Expand All @@ -656,10 +654,6 @@ def simulate_cmd(
# 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)

Expand Down Expand Up @@ -693,7 +687,6 @@ def simulate_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.
Expand All @@ -702,16 +695,11 @@ def simulate(

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}})
"""

Expand All @@ -730,7 +718,6 @@ def simulate(

om_cmd = self.simulate_cmd(
result_file=self._result_file,
simflags=simflags,
simargs=simargs,
)

Expand Down Expand Up @@ -1060,7 +1047,6 @@ def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC:
def linearize(
self,
lintime: Optional[float] = None,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
) -> LinearizationResult:
"""Linearize the model according to linearization options.
Expand All @@ -1069,8 +1055,6 @@ def linearize(

Args:
lintime: Override "stopTime" value.
simflags: String of extra command line flags for the model binary.
This argument is deprecated, use simargs instead.
simargs: A dict with command line flags and possible options; example: "simargs={'csvInput': 'a.csv'}"

Returns:
Expand Down Expand Up @@ -1123,10 +1107,6 @@ def linearize(
f"<= lintime <= {self._linearization_options['stopTime']}")
om_cmd.arg_set(key="l", val=str(lintime))

# 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)

Expand Down
Loading
Loading