Skip to content

Commit c8ffa8f

Browse files
committed
G005-remove_depreciated_functionality2
[OMCSessionABC] remove execute(); still available in compatibility v4.0.0 [ModelicaSystem] define _set_compatibility_helper() as static [ModelExecutionCmd] remove depreciated simflags [test_ModelSystemCmd/ModelExecutionCmd] fix test due to changes [ModelicaSystemCmd] cleanup - do not define (unused / not useable) class
1 parent e2f18f2 commit c8ffa8f

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__)
@@ -306,45 +305,3 @@ def definition(self) -> ModelExecutionData:
306305
)
307306

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

OMPython/modelica_system_abc.py

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,6 @@ def _process_override_data(
620620
def simulate_cmd(
621621
self,
622622
result_file: OMPathABC,
623-
simflags: Optional[str] = None,
624623
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
625624
) -> ModelExecutionCmd:
626625
"""
@@ -636,7 +635,6 @@ def simulate_cmd(
636635
Parameters
637636
----------
638637
result_file
639-
simflags
640638
simargs
641639
642640
Returns
@@ -656,10 +654,6 @@ def simulate_cmd(
656654
# always define the result file to use
657655
om_cmd.arg_set(key="r", val=result_file.as_posix())
658656

659-
# allow runtime simulation flags from user input
660-
if simflags is not None:
661-
om_cmd.args_set(args=om_cmd.parse_simflags(simflags=simflags))
662-
663657
if simargs:
664658
om_cmd.args_set(args=simargs)
665659

@@ -693,7 +687,6 @@ def simulate_cmd(
693687
def simulate(
694688
self,
695689
resultfile: Optional[str | os.PathLike] = None,
696-
simflags: Optional[str] = None,
697690
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
698691
) -> None:
699692
"""Simulate the model according to simulation options.
@@ -702,16 +695,11 @@ def simulate(
702695
703696
Args:
704697
resultfile: Path to a custom result file
705-
simflags: String of extra command line flags for the model binary.
706-
This argument is deprecated, use simargs instead.
707698
simargs: Dict with simulation runtime flags.
708699
709700
Examples:
710701
mod.simulate()
711702
mod.simulate(resultfile="a.mat")
712-
# set runtime simulation flags, deprecated
713-
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10")
714-
# using simargs
715703
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}})
716704
"""
717705

@@ -730,7 +718,6 @@ def simulate(
730718

731719
om_cmd = self.simulate_cmd(
732720
result_file=self._result_file,
733-
simflags=simflags,
734721
simargs=simargs,
735722
)
736723

@@ -1060,7 +1047,6 @@ def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC:
10601047
def linearize(
10611048
self,
10621049
lintime: Optional[float] = None,
1063-
simflags: Optional[str] = None,
10641050
simargs: Optional[dict[str, Optional[str | dict[str, Any] | numbers.Number]]] = None,
10651051
) -> LinearizationResult:
10661052
"""Linearize the model according to linearization options.
@@ -1069,8 +1055,6 @@ def linearize(
10691055
10701056
Args:
10711057
lintime: Override "stopTime" value.
1072-
simflags: String of extra command line flags for the model binary.
1073-
This argument is deprecated, use simargs instead.
10741058
simargs: A dict with command line flags and possible options; example: "simargs={'csvInput': 'a.csv'}"
10751059
10761060
Returns:
@@ -1123,10 +1107,6 @@ def linearize(
11231107
f"<= lintime <= {self._linearization_options['stopTime']}")
11241108
om_cmd.arg_set(key="l", val=str(lintime))
11251109

1126-
# allow runtime simulation flags from user input
1127-
if simflags is not None:
1128-
om_cmd.args_set(args=om_cmd.parse_simflags(simflags=simflags))
1129-
11301110
if simargs:
11311111
om_cmd.args_set(args=simargs)
11321112

0 commit comments

Comments
 (0)