Skip to content

Commit a9206d3

Browse files
committed
G004-remove_deprecated-ModelicaSystem_rewrite_set_functions2
[ModelicaSystemABC] remove code for (depreciated) arguments in set*() methods * define code in the compatibility layer in class ModelicaSystem [test_ModelicaSystem(OMC)] update tests * for new version: remove usage of old definition * for compatibility version: test old definition
1 parent 6d738a4 commit a9206d3

5 files changed

Lines changed: 85 additions & 126 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,62 @@ def _set_compatibility_helper(
7777
pkey: str,
7878
args: Any,
7979
kwargs: dict[str, Any],
80-
) -> Any:
81-
param = None
80+
) -> dict[str, Any]:
81+
input_args = []
8282
if len(args) == 1:
83-
param = args[0]
84-
if param is None and pkey in kwargs:
85-
param = kwargs[pkey]
86-
87-
return param
83+
input_args.append(args[0])
84+
elif pkey in kwargs:
85+
input_args.append(kwargs[pkey])
86+
87+
# the code below is based on _prepare_input_data2()
88+
89+
def prepare_str(str_in: str) -> dict[str, str]:
90+
str_in = str_in.replace(" ", "")
91+
key_val_list: list[str] = str_in.split("=")
92+
if len(key_val_list) != 2:
93+
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
94+
if len(key_val_list[0]) == 0:
95+
raise ModelicaSystemError(f"Empty key: {str_in}")
96+
97+
input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}
98+
99+
return input_data_from_str
100+
101+
input_data: dict[str, str] = {}
102+
103+
if input_args is None:
104+
return input_data
105+
106+
for input_arg in input_args:
107+
if isinstance(input_arg, str):
108+
warnings.warn(message="The definition of values to set should use a dictionary, "
109+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
110+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
111+
category=DeprecationWarning,
112+
stacklevel=3)
113+
input_data = input_data | prepare_str(input_arg)
114+
elif isinstance(input_arg, list):
115+
warnings.warn(message="The definition of values to set should use a dictionary, "
116+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
117+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
118+
category=DeprecationWarning,
119+
stacklevel=3)
120+
121+
for item in input_arg:
122+
if not isinstance(item, str):
123+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
124+
input_data = input_data | prepare_str(item)
125+
elif isinstance(input_arg, dict):
126+
input_arg_str: dict[str, str] = {}
127+
for key, val in input_arg.items():
128+
if not isinstance(key, str) or len(key) == 0:
129+
raise ModelicaSystemError(f"Invalid key for set*() functions: {repr(key)}")
130+
input_arg_str[key] = str(val).replace(' ', '')
131+
input_data = input_data | input_arg_str
132+
else:
133+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")
134+
135+
return input_data
88136

89137
def setContinuous(
90138
self,
@@ -104,10 +152,7 @@ def setContinuous(
104152
```
105153
"""
106154
param = self._set_compatibility_helper(pkey='cvals', args=args, kwargs=kwargs)
107-
if param is None:
108-
raise ModelicaSystemError("Invalid input for setContinuous() (v4.0.0 compatibility mode).")
109-
110-
return super().setContinuous(param)
155+
return super().setContinuous(**param)
111156

112157
def setParameters(
113158
self,
@@ -127,10 +172,7 @@ def setParameters(
127172
```
128173
"""
129174
param = self._set_compatibility_helper(pkey='pvals', args=args, kwargs=kwargs)
130-
if param is None:
131-
raise ModelicaSystemError("Invalid input for setParameters() (v4.0.0 compatibility mode).")
132-
133-
return super().setParameters(param)
175+
return super().setParameters(**param)
134176

135177
def setOptimizationOptions(
136178
self,
@@ -150,10 +192,7 @@ def setOptimizationOptions(
150192
```
151193
"""
152194
param = self._set_compatibility_helper(pkey='optimizationOptions', args=args, kwargs=kwargs)
153-
if param is None:
154-
raise ModelicaSystemError("Invalid input for setOptimizationOptions() (v4.0.0 compatibility mode).")
155-
156-
return super().setOptimizationOptions(param)
195+
return super().setOptimizationOptions(**param)
157196

158197
def setInputs(
159198
self,
@@ -173,10 +212,7 @@ def setInputs(
173212
```
174213
"""
175214
param = self._set_compatibility_helper(pkey='name', args=args, kwargs=kwargs)
176-
if param is None:
177-
raise ModelicaSystemError("Invalid input for setInputs() (v4.0.0 compatibility mode).")
178-
179-
return super().setInputs(param)
215+
return super().setInputs(**param)
180216

181217
def setSimulationOptions(
182218
self,
@@ -196,10 +232,7 @@ def setSimulationOptions(
196232
```
197233
"""
198234
param = self._set_compatibility_helper(pkey='simOptions', args=args, kwargs=kwargs)
199-
if param is None:
200-
raise ModelicaSystemError("Invalid input for setSimulationOptions() (v4.0.0 compatibility mode).")
201-
202-
return super().setSimulationOptions(param)
235+
return super().setSimulationOptions(**param)
203236

204237
def setLinearizationOptions(
205238
self,
@@ -219,10 +252,7 @@ def setLinearizationOptions(
219252
```
220253
"""
221254
param = self._set_compatibility_helper(pkey='linearizationOptions', args=args, kwargs=kwargs)
222-
if param is None:
223-
raise ModelicaSystemError("Invalid input for setLinearizationOptions() (v4.0.0 compatibility mode).")
224-
225-
return super().setLinearizationOptions(param)
255+
return super().setLinearizationOptions(**param)
226256

227257
def getContinuous(
228258
self,

OMPython/modelica_doe_abc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def prepare(self) -> int:
210210
}
211211
)
212212

213-
self._mod.setParameters(sim_param_non_structural)
213+
self._mod.setParameters(**sim_param_non_structural)
214214
mscmd = self._mod.simulate_cmd(
215215
result_file=resultfile,
216216
)

OMPython/modelica_system_abc.py

Lines changed: 20 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import os
1212
import re
1313
from typing import Any, Optional
14-
import warnings
1514
import xml.etree.ElementTree as ET
1615

1716
import numpy as np
@@ -753,56 +752,13 @@ def simulate(
753752

754753
@staticmethod
755754
def _prepare_input_data(
756-
input_args: Any,
757755
input_kwargs: dict[str, Any],
758756
) -> dict[str, str]:
759757
"""
760758
Convert raw input to a structured dictionary {'key1': 'value1', 'key2': 'value2'}.
761759
"""
762-
763-
def prepare_str(str_in: str) -> dict[str, str]:
764-
str_in = str_in.replace(" ", "")
765-
key_val_list: list[str] = str_in.split("=")
766-
if len(key_val_list) != 2:
767-
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
768-
if len(key_val_list[0]) == 0:
769-
raise ModelicaSystemError(f"Empty key: {str_in}")
770-
771-
input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}
772-
773-
return input_data_from_str
774-
775760
input_data: dict[str, str] = {}
776761

777-
for input_arg in input_args:
778-
if isinstance(input_arg, str):
779-
warnings.warn(message="The definition of values to set should use a dictionary, "
780-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
781-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
782-
category=DeprecationWarning,
783-
stacklevel=3)
784-
input_data = input_data | prepare_str(input_arg)
785-
elif isinstance(input_arg, list):
786-
warnings.warn(message="The definition of values to set should use a dictionary, "
787-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
788-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
789-
category=DeprecationWarning,
790-
stacklevel=3)
791-
792-
for item in input_arg:
793-
if not isinstance(item, str):
794-
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
795-
input_data = input_data | prepare_str(item)
796-
elif isinstance(input_arg, dict):
797-
input_arg_str: dict[str, str] = {}
798-
for key, val in input_arg.items():
799-
if not isinstance(key, str) or len(key) == 0:
800-
raise ModelicaSystemError(f"Invalid key for set*() functions: {repr(key)}")
801-
input_arg_str[key] = str(val)
802-
input_data = input_data | input_arg_str
803-
else:
804-
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")
805-
806762
if len(input_kwargs):
807763
for key, val in input_kwargs.items():
808764
# ensure all values are strings to align it on one type: dict[str, str]
@@ -880,21 +836,17 @@ def isParameterChangeable(
880836

881837
def setContinuous(
882838
self,
883-
*args: Any,
884839
**kwargs: dict[str, Any],
885840
) -> bool:
886841
"""
887-
This method is used to set continuous values. It can be called:
888-
with a sequence of continuous name and assigning corresponding values as arguments as show in the example below:
889-
usage
890-
>>> setContinuous("Name=value") # depreciated
891-
>>> setContinuous(["Name1=value1","Name2=value2"]) # depreciated
842+
This method is used to set continuous values.
892843
844+
usage:
893845
>>> setContinuous(Name1="value1", Name2="value2")
894846
>>> param = {"Name1": "value1", "Name2": "value2"}
895847
>>> setContinuous(**param)
896848
"""
897-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
849+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
898850

899851
return self._set_method_helper(
900852
inputdata=inputdata,
@@ -904,21 +856,17 @@ def setContinuous(
904856

905857
def setParameters(
906858
self,
907-
*args: Any,
908859
**kwargs: dict[str, Any],
909860
) -> bool:
910861
"""
911-
This method is used to set parameter values. It can be called:
912-
with a sequence of parameter name and assigning corresponding value as arguments as show in the example below:
913-
usage
914-
>>> setParameters("Name=value") # depreciated
915-
>>> setParameters(["Name1=value1","Name2=value2"]) # depreciated
862+
This method is used to set parameter values
916863
864+
usage:
917865
>>> setParameters(Name1="value1", Name2="value2")
918866
>>> param = {"Name1": "value1", "Name2": "value2"}
919867
>>> setParameters(**param)
920868
"""
921-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
869+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
922870

923871
return self._set_method_helper(
924872
inputdata=inputdata,
@@ -928,22 +876,17 @@ def setParameters(
928876

929877
def setSimulationOptions(
930878
self,
931-
*args: Any,
932879
**kwargs: dict[str, Any],
933880
) -> bool:
934881
"""
935-
This method is used to set simulation options. It can be called:
936-
with a sequence of simulation options name and assigning corresponding values as arguments as show in the
937-
example below:
938-
usage
939-
>>> setSimulationOptions("Name=value") # depreciated
940-
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
882+
This method is used to set simulation options.
941883
884+
usage:
942885
>>> setSimulationOptions(Name1="value1", Name2="value2")
943886
>>> param = {"Name1": "value1", "Name2": "value2"}
944887
>>> setSimulationOptions(**param)
945888
"""
946-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
889+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
947890

948891
return self._set_method_helper(
949892
inputdata=inputdata,
@@ -953,22 +896,17 @@ def setSimulationOptions(
953896

954897
def setLinearizationOptions(
955898
self,
956-
*args: Any,
957899
**kwargs: dict[str, Any],
958900
) -> bool:
959901
"""
960-
This method is used to set linearization options. It can be called:
961-
with a sequence of linearization options name and assigning corresponding value as arguments as show in the
962-
example below
963-
usage
964-
>>> setLinearizationOptions("Name=value") # depreciated
965-
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
902+
This method is used to set linearization options.
966903
904+
usage:
967905
>>> setLinearizationOptions(Name1="value1", Name2="value2")
968906
>>> param = {"Name1": "value1", "Name2": "value2"}
969907
>>> setLinearizationOptions(**param)
970908
"""
971-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
909+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
972910

973911
return self._set_method_helper(
974912
inputdata=inputdata,
@@ -978,22 +916,17 @@ def setLinearizationOptions(
978916

979917
def setOptimizationOptions(
980918
self,
981-
*args: Any,
982919
**kwargs: dict[str, Any],
983920
) -> bool:
984921
"""
985-
This method is used to set optimization options. It can be called:
986-
with a sequence of optimization options name and assigning corresponding values as arguments as show in the
987-
example below:
988-
usage
989-
>>> setOptimizationOptions("Name=value") # depreciated
990-
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
922+
This method is used to set optimization options.
991923
924+
usage:
992925
>>> setOptimizationOptions(Name1="value1", Name2="value2")
993926
>>> param = {"Name1": "value1", "Name2": "value2"}
994927
>>> setOptimizationOptions(**param)
995928
"""
996-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
929+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
997930

998931
return self._set_method_helper(
999932
inputdata=inputdata,
@@ -1007,19 +940,17 @@ def setInputs(
1007940
**kwargs: dict[str, Any],
1008941
) -> bool:
1009942
"""
1010-
This method is used to set input values. It can be called with a sequence of input name and assigning
1011-
corresponding values as arguments as show in the example below. Compared to other set*() methods this is a
1012-
special case as value could be a list of tuples - these are converted to a string in _prepare_input_data()
1013-
and restored here via ast.literal_eval().
943+
This method is used to set input values.
1014944
1015-
>>> setInputs("Name=value") # depreciated
1016-
>>> setInputs(["Name1=value1","Name2=value2"]) # depreciated
945+
Compared to other set*() methods this is a special case as value could be a list of tuples - these are
946+
converted to a string in _prepare_input_data() and restored here via ast.literal_eval().
1017947
948+
usage:
1018949
>>> setInputs(Name1="value1", Name2="value2")
1019950
>>> param = {"Name1": "value1", "Name2": "value2"}
1020951
>>> setInputs(**param)
1021952
"""
1022-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
953+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
1023954

1024955
for key, val in inputdata.items():
1025956
if key not in self._inputs:

tests/test_ModelicaSystemOMC.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,8 @@ def test_setParameters():
6464
model_name="BouncingBall",
6565
)
6666

67-
# method 1 (test depreciated variants)
68-
mod.setParameters("e=1.234")
69-
mod.setParameters(["g=321.0"])
67+
mod.setParameters(e=1.234)
68+
mod.setParameters(g=321.0)
7069
assert mod.getParameters("e") == ["1.234"]
7170
assert mod.getParameters("g") == ["321.0"]
7271
assert mod.getParameters() == {
@@ -76,7 +75,6 @@ def test_setParameters():
7675
with pytest.raises(KeyError):
7776
mod.getParameters("thisParameterDoesNotExist")
7877

79-
# method 2 (new style)
8078
pvals = {"e": 21.3, "g": 0.12}
8179
mod.setParameters(**pvals)
8280
assert mod.getParameters() == {

tests_v400/test_ModelicaSystem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def test_setParameters():
3535
mod = OMPython.ModelicaSystem(model_path + "BouncingBall.mo", "BouncingBall")
3636

3737
# method 1
38-
mod.setParameters(pvals={"e": 1.234})
38+
mod.setParameters(pvals="e=1.234")
3939
mod.setParameters(pvals={"g": 321.0})
4040
assert mod.getParameters("e") == ["1.234"]
4141
assert mod.getParameters("g") == ["321.0"]

0 commit comments

Comments
 (0)