Skip to content
Open
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
233 changes: 195 additions & 38 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
import pathlib
import platform
from typing import Any, Optional
import warnings

import numpy as np

from OMPython.model_execution import (
ModelExecutionCmd,
ModelExecutionConfig,
ModelExecutionException,
)
from OMPython.om_session_omc import (
Expand All @@ -28,10 +29,15 @@
ModelicaDoEOMC,
)

from OMPython.compatibility_v400 import (
depreciated_class,
)

# define logger using the current module name as ID
logger = logging.getLogger(__name__)


@depreciated_class(msg="Please use class ModelicaSystemOMC instead!")
class ModelicaSystem(ModelicaSystemOMC):
"""
Compatibility class.
Expand Down Expand Up @@ -67,58 +73,197 @@ def __init__(
def setCommandLineOptions(self, commandLineOptions: str):
super().set_command_line_options(command_line_option=commandLineOptions)

def setContinuous( # type: ignore[override]
def _set_compatibility_helper(
self,
pkey: str,
args: Any,
kwargs: dict[str, Any],
) -> dict[str, Any]:
input_args = []
if len(args) == 1:
input_args.append(args[0])
elif pkey in kwargs:
input_args.append(kwargs[pkey])

# the code below is based on _prepare_input_data2()

def prepare_str(str_in: str) -> dict[str, str]:
str_in = str_in.replace(" ", "")
key_val_list: list[str] = str_in.split("=")
if len(key_val_list) != 2:
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
if len(key_val_list[0]) == 0:
raise ModelicaSystemError(f"Empty key: {str_in}")

input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}

return input_data_from_str

input_data: dict[str, str] = {}

if input_args is None:
return input_data

for input_arg in input_args:
if isinstance(input_arg, str):
warnings.warn(message="The definition of values to set should use a dictionary, "
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
category=DeprecationWarning,
stacklevel=3)
input_data = input_data | prepare_str(input_arg)
elif isinstance(input_arg, list):
warnings.warn(message="The definition of values to set should use a dictionary, "
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
category=DeprecationWarning,
stacklevel=3)

for item in input_arg:
if not isinstance(item, str):
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
input_data = input_data | prepare_str(item)
elif isinstance(input_arg, dict):
input_arg_str: dict[str, str] = {}
for key, val in input_arg.items():
if not isinstance(key, str) or len(key) == 0:
raise ModelicaSystemError(f"Invalid key for set*() functions: {repr(key)}")
input_arg_str[key] = str(val).replace(' ', '')
input_data = input_data | input_arg_str
else:
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")

return input_data

def setContinuous(
self,
cvals: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(cvals, dict):
return super().setContinuous(**cvals)
raise ModelicaSystemError("Only dict input supported for setContinuous()")
"""
Compatibility wrapper for setContinuous() from OMPython v4.0.0

Original definition:

def setParameters( # type: ignore[override]
```
def setContinuous(
self,
cvals: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='cvals', args=args, kwargs=kwargs)
return super().setContinuous(**param)

def setParameters(
self,
pvals: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(pvals, dict):
return super().setParameters(**pvals)
raise ModelicaSystemError("Only dict input supported for setParameters()")
"""
Compatibility wrapper for setParameters() from OMPython v4.0.0

Original definition:

def setOptimizationOptions( # type: ignore[override]
```
def setParameters(
self,
pvals: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='pvals', args=args, kwargs=kwargs)
return super().setParameters(**param)

def setOptimizationOptions(
self,
optimizationOptions: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(optimizationOptions, dict):
return super().setOptimizationOptions(**optimizationOptions)
raise ModelicaSystemError("Only dict input supported for setOptimizationOptions()")
"""
Compatibility wrapper for setOptimizationOptions() from OMPython v4.0.0

Original definition:

def setInputs( # type: ignore[override]
```
def setOptimizationOptions(
self,
optimizationOptions: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='optimizationOptions', args=args, kwargs=kwargs)
return super().setOptimizationOptions(**param)

def setInputs(
self,
name: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(name, dict):
return super().setInputs(**name)
raise ModelicaSystemError("Only dict input supported for setInputs()")
"""
Compatibility wrapper for setInputs() from OMPython v4.0.0

Original definition:

def setSimulationOptions( # type: ignore[override]
```
def setInputs(
self,
name: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='name', args=args, kwargs=kwargs)
return super().setInputs(**param)

def setSimulationOptions(
self,
simOptions: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(simOptions, dict):
return super().setSimulationOptions(**simOptions)
raise ModelicaSystemError("Only dict input supported for setSimulationOptions()")
"""
Compatibility wrapper for setSimulationOptions() from OMPython v4.0.0

def setLinearizationOptions( # type: ignore[override]
Original definition:

```
def setSimulationOptions(
self,
simOptions: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='simOptions', args=args, kwargs=kwargs)
return super().setSimulationOptions(**param)

def setLinearizationOptions(
self,
linearizationOptions: str | list[str] | dict[str, Any],
*args: Any,
**kwargs: dict[str, Any],
) -> bool:
if isinstance(linearizationOptions, dict):
return super().setLinearizationOptions(**linearizationOptions)
raise ModelicaSystemError("Only dict input supported for setLinearizationOptions()")
"""
Compatibility wrapper for setLinearizationOptions() from OMPython v4.0.0

Original definition:

```
def setLinearizationOptions(
self,
linearizationOptions: str | list[str] | dict[str, Any],
) -> bool:
```
"""
param = self._set_compatibility_helper(pkey='linearizationOptions', args=args, kwargs=kwargs)
return super().setLinearizationOptions(**param)

def getContinuous(
self,
names: Optional[str | list[str]] = None,
):
"""
Compatibility wrapper for getContinuous() from OMPython v4.0.0

If no model simulation was run (self._simulated == False), the return value should be converted to str.
"""
retval = super().getContinuous(names=names)
if self._simulated:
return retval
Expand All @@ -140,12 +285,17 @@ def getContinuous(
retval3.append(str(val))
return retval3

raise ModelExecutionException("Invalid data!")
raise ModelicaSystemError("Invalid data!")

def getOutputs(
self,
names: Optional[str | list[str]] = None,
):
"""
Compatibility wrapper for getOutputs() from OMPython v4.0.0

If no model simulation was run (self._simulated == False), the return value should be converted to str.
"""
retval = super().getOutputs(names=names)
if self._simulated:
return retval
Expand All @@ -167,18 +317,20 @@ def getOutputs(
retval3.append(str(val))
return retval3

raise ModelExecutionException("Invalid data!")
raise ModelicaSystemError("Invalid data!")


@depreciated_class(msg="Please use class ModelicaDoEOMC instead!")
class ModelicaSystemDoE(ModelicaDoEOMC):
"""
Compatibility class.
"""


class ModelicaSystemCmd(ModelExecutionCmd):
@depreciated_class(msg="Please use class ModelExecutionConfig instead!")
class ModelicaSystemCmd(ModelExecutionConfig):
"""
Compatibility class; in the new version it is renamed as ModelExecutionCmd.
Compatibility class; in the new version it is renamed as ModelExecutionConfig.
"""

def __init__(
Expand Down Expand Up @@ -209,7 +361,8 @@ def get_exe(self) -> pathlib.Path:
return path_exe

def get_cmd(self) -> list:
"""Get a list with the path to the executable and all command line args.
"""
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().
"""
Expand All @@ -218,6 +371,10 @@ def get_cmd(self) -> list:

return cmdl

def run(self):
def run(self) -> int:
cmd_definition = self.definition()
return cmd_definition.run()
try:
returncode = cmd_definition.run()
except ModelExecutionException as exc:
raise ModelicaSystemError(f"Cannot execute model: {exc}") from exc
return returncode
Loading
Loading