Skip to content

Commit 8f3fe83

Browse files
committed
Merge branch 'G005-remove_depreciated_functionality2' into syntron-RFC3
2 parents 036274f + 098b89a commit 8f3fe83

9 files changed

Lines changed: 146 additions & 140 deletions

OMPython/ModelicaSystem.py

Lines changed: 117 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,26 @@
44
"""
55

66
import logging
7+
import numbers
78
import os
89
import pathlib
9-
import platform
1010
from typing import Any, Optional
11+
import warnings
1112

1213
import numpy as np
1314

1415
from OMPython.model_execution import (
1516
ModelExecutionCmd,
1617
ModelExecutionException,
1718
)
19+
from OMPython.om_session_abc import (
20+
OMPathABC,
21+
)
1822
from OMPython.om_session_omc import (
1923
OMCSessionLocal,
2024
)
2125
from OMPython.modelica_system_abc import (
26+
LinearizationResult,
2227
ModelicaSystemError,
2328
)
2429
from OMPython.modelica_system_omc import (
@@ -72,8 +77,73 @@ def __init__(
7277
def setCommandLineOptions(self, commandLineOptions: str):
7378
super().set_command_line_options(command_line_option=commandLineOptions)
7479

75-
def _set_compatibility_helper(
80+
def simulate_cmd( # type: ignore[override]
81+
self,
82+
result_file: OMPathABC,
83+
simflags: Optional[str] = None,
84+
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
85+
) -> ModelExecutionCmd:
86+
"""
87+
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
88+
"""
89+
90+
if simargs is None:
91+
simargs = {}
92+
93+
if simflags is not None:
94+
simargs_extra = parse_simflags(simflags=simflags)
95+
simargs = simargs | simargs_extra
96+
97+
return super().simulate_cmd(
98+
result_file=result_file,
99+
simargs=simargs,
100+
)
101+
102+
def simulate( # type: ignore[override]
103+
self,
104+
resultfile: Optional[str | os.PathLike] = None,
105+
simflags: Optional[str] = None,
106+
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
107+
) -> None:
108+
"""
109+
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
110+
"""
111+
112+
if simargs is None:
113+
simargs = {}
114+
115+
if simflags is not None:
116+
simargs_extra = parse_simflags(simflags=simflags)
117+
simargs = simargs | simargs_extra
118+
119+
return super().simulate(
120+
resultfile=resultfile,
121+
simargs=simargs,
122+
)
123+
124+
def linearize( # type: ignore[override]
76125
self,
126+
lintime: Optional[float] = None,
127+
simflags: Optional[str] = None,
128+
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
129+
) -> LinearizationResult:
130+
"""
131+
Compatibility layer for OMPython v4.0.0 - keep simflags available and use ModelicaSystemCmd!
132+
"""
133+
if simargs is None:
134+
simargs = {}
135+
136+
if simflags is not None:
137+
simargs_extra = parse_simflags(simflags=simflags)
138+
simargs = simargs | simargs_extra
139+
140+
return super().linearize(
141+
lintime=lintime,
142+
simargs=simargs,
143+
)
144+
145+
@staticmethod
146+
def _set_compatibility_helper(
77147
pkey: str,
78148
args: Any,
79149
kwargs: dict[str, Any],
@@ -329,51 +399,52 @@ class ModelicaSystemDoE(ModelicaDoEOMC):
329399
@depreciated_class(msg="Please use class ModelExecutionCmd instead!")
330400
class ModelicaSystemCmd(ModelExecutionCmd):
331401
"""
332-
Compatibility class; in the new version it is renamed as ModelExecutionCmd.
333-
"""
334-
335-
def __init__(
336-
self,
337-
runpath: pathlib.Path,
338-
modelname: str,
339-
timeout: float = 10.0,
340-
) -> None:
341-
super().__init__(
342-
runpath=runpath,
343-
timeout=timeout,
344-
cmd_prefix=[],
345-
model_name=modelname,
346-
)
402+
Compatibility class; not much content.
347403
348-
def get_exe(self) -> pathlib.Path:
349-
"""Get the path to the compiled model executable."""
350-
351-
path_run = pathlib.Path(self._runpath)
352-
if platform.system() == "Windows":
353-
path_exe = path_run / f"{self._model_name}.exe"
354-
else:
355-
path_exe = path_run / self._model_name
356-
357-
if not path_exe.exists():
358-
raise ModelicaSystemError(f"Application file path not found: {path_exe}")
359-
360-
return path_exe
361-
362-
def get_cmd(self) -> list:
363-
"""
364-
Get a list with the path to the executable and all command line args.
365-
366-
This can later be used as an argument for subprocess.run().
367-
"""
404+
Missing definitions:
405+
* get_exe() - see self.definition.cmd_model_executable
406+
* get_cmd() - use self.get_cmd_args() or self.definition().get_cmd()
407+
* run() - use self.definition().run()
408+
"""
368409

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

371-
return cmdl
411+
def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, Any] | numbers.Number]]:
412+
"""
413+
Parse a simflag definition; this is deprecated!
372414
373-
def run(self) -> int:
374-
cmd_definition = self.definition()
375-
try:
376-
returncode = cmd_definition.run()
377-
except ModelExecutionException as exc:
378-
raise ModelicaSystemError(f"Cannot execute model: {exc}") from exc
379-
return returncode
415+
The return data can be used as input for self.args_set().
416+
"""
417+
warnings.warn(
418+
message="The argument 'simflags' is depreciated and will be removed in future versions; "
419+
"please use 'simargs' instead",
420+
category=DeprecationWarning,
421+
stacklevel=2,
422+
)
423+
424+
simargs: dict[str, Optional[str | dict[str, Any] | numbers.Number]] = {}
425+
426+
args = [s for s in simflags.split(' ') if s]
427+
for arg in args:
428+
if arg[0] != '-':
429+
raise ModelExecutionException(f"Invalid simulation flag: {arg}")
430+
arg = arg[1:]
431+
parts = arg.split('=')
432+
if len(parts) == 1:
433+
simargs[parts[0]] = None
434+
elif parts[0] == 'override':
435+
override = '='.join(parts[1:])
436+
437+
override_dict = {}
438+
for item in override.split(','):
439+
kv = item.split('=')
440+
if not 0 < len(kv) < 3:
441+
raise ModelExecutionException(f"Invalid value for '-override': {override}")
442+
if kv[0]:
443+
try:
444+
override_dict[kv[0]] = kv[1]
445+
except (KeyError, IndexError) as ex:
446+
raise ModelExecutionException(f"Invalid value for '-override': {override}") from ex
447+
448+
simargs[parts[0]] = override_dict
449+
450+
return simargs

OMPython/OMCSession.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import logging
99
from typing import Any, Optional
10+
import warnings
1011

1112
import pyparsing
1213

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

274275
def execute(self, command: str):
275-
return self.omc_process.execute(command=command)
276+
warnings.warn(
277+
message="This function is depreciated and will be removed in future versions; "
278+
"please use sendExpression() instead",
279+
category=DeprecationWarning,
280+
stacklevel=2,
281+
)
282+
return self.omc_process.sendExpression(expr=command, parsed=False)
276283

277284
def sendExpression(self, command: str, parsed: bool = True) -> Any: # pylint: disable=W0237
278285
"""

OMPython/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@
6161
# the imports below are compatibility functionality (OMPython v4.0.0)
6262
from OMPython.ModelicaSystem import (
6363
ModelicaSystem,
64-
ModelicaSystemCmd,
6564
ModelicaSystemDoE,
65+
parse_simflags,
6666
)
6767
from OMPython.OMCSession import (
6868
OMCSessionCmd,
@@ -109,9 +109,9 @@
109109
'OMPathRunnerLocal',
110110
'OMSessionRunner',
111111

112-
'ModelicaSystemCmd',
113112
'ModelicaSystem',
114113
'ModelicaSystemDoE',
114+
'parse_simflags',
115115

116116
'OMCSessionCmd',
117117

OMPython/model_execution.py

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import re
1313
import subprocess
1414
from typing import Any, Optional
15-
import warnings
1615

1716
# define logger using the current module name as ID
1817
logger = logging.getLogger(__name__)
@@ -305,45 +304,3 @@ def definition(self) -> ModelExecutionData:
305304
)
306305

307306
return omc_run_data
308-
309-
@staticmethod
310-
def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, Any] | numbers.Number]]:
311-
"""
312-
Parse a simflag definition; this is deprecated!
313-
314-
The return data can be used as input for self.args_set().
315-
"""
316-
warnings.warn(
317-
message="The argument 'simflags' is depreciated and will be removed in future versions; "
318-
"please use 'simargs' instead",
319-
category=DeprecationWarning,
320-
stacklevel=2,
321-
)
322-
323-
simargs: dict[str, Optional[str | dict[str, Any] | numbers.Number]] = {}
324-
325-
args = [s for s in simflags.split(' ') if s]
326-
for arg in args:
327-
if arg[0] != '-':
328-
raise ModelExecutionException(f"Invalid simulation flag: {arg}")
329-
arg = arg[1:]
330-
parts = arg.split('=')
331-
if len(parts) == 1:
332-
simargs[parts[0]] = None
333-
elif parts[0] == 'override':
334-
override = '='.join(parts[1:])
335-
336-
override_dict = {}
337-
for item in override.split(','):
338-
kv = item.split('=')
339-
if not 0 < len(kv) < 3:
340-
raise ModelExecutionException(f"Invalid value for '-override': {override}")
341-
if kv[0]:
342-
try:
343-
override_dict[kv[0]] = kv[1]
344-
except (KeyError, IndexError) as ex:
345-
raise ModelExecutionException(f"Invalid value for '-override': {override}") from ex
346-
347-
simargs[parts[0]] = override_dict
348-
349-
return simargs

OMPython/modelica_system_abc.py

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,6 @@ def _process_override_data(
615615
def simulate_cmd(
616616
self,
617617
result_file: OMPathABC,
618-
simflags: Optional[str] = None,
619618
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
620619
) -> ModelExecutionCmd:
621620
"""
@@ -631,7 +630,6 @@ def simulate_cmd(
631630
Parameters
632631
----------
633632
result_file
634-
simflags
635633
simargs
636634
637635
Returns
@@ -650,10 +648,6 @@ def simulate_cmd(
650648
# always define the result file to use
651649
om_cmd.arg_set(key="r", val=result_file.as_posix())
652650

653-
# allow runtime simulation flags from user input
654-
if simflags is not None:
655-
om_cmd.args_set(args=om_cmd.parse_simflags(simflags=simflags))
656-
657651
if simargs:
658652
om_cmd.args_set(args=simargs)
659653

@@ -687,7 +681,6 @@ def simulate_cmd(
687681
def simulate(
688682
self,
689683
resultfile: Optional[str | os.PathLike] = None,
690-
simflags: Optional[str] = None,
691684
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
692685
) -> None:
693686
"""Simulate the model according to simulation options.
@@ -696,16 +689,11 @@ def simulate(
696689
697690
Args:
698691
resultfile: Path to a custom result file
699-
simflags: String of extra command line flags for the model binary.
700-
This argument is deprecated, use simargs instead.
701692
simargs: Dict with simulation runtime flags.
702693
703694
Examples:
704695
mod.simulate()
705696
mod.simulate(resultfile="a.mat")
706-
# set runtime simulation flags, deprecated
707-
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10")
708-
# using simargs
709697
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}})
710698
"""
711699

@@ -724,7 +712,6 @@ def simulate(
724712

725713
om_cmd = self.simulate_cmd(
726714
result_file=self._result_file,
727-
simflags=simflags,
728715
simargs=simargs,
729716
)
730717

@@ -1054,7 +1041,6 @@ def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC:
10541041
def linearize(
10551042
self,
10561043
lintime: Optional[float] = None,
1057-
simflags: Optional[str] = None,
10581044
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
10591045
) -> LinearizationResult:
10601046
"""Linearize the model according to linearization options.
@@ -1063,8 +1049,6 @@ def linearize(
10631049
10641050
Args:
10651051
lintime: Override "stopTime" value.
1066-
simflags: String of extra command line flags for the model binary.
1067-
This argument is deprecated, use simargs instead.
10681052
simargs: A dict with command line flags and possible options; example: "simargs={'csvInput': 'a.csv'}"
10691053
10701054
Returns:
@@ -1116,10 +1100,6 @@ def linearize(
11161100
f"<= lintime <= {self._linearization_options['stopTime']}")
11171101
om_cmd.arg_set(key="l", val=str(lintime))
11181102

1119-
# allow runtime simulation flags from user input
1120-
if simflags is not None:
1121-
om_cmd.args_set(args=om_cmd.parse_simflags(simflags=simflags))
1122-
11231103
if simargs:
11241104
om_cmd.args_set(args=simargs)
11251105

0 commit comments

Comments
 (0)