Skip to content

Commit e2f18f2

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 d867214 commit e2f18f2

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
@@ -759,56 +758,13 @@ def simulate(
759758

760759
@staticmethod
761760
def _prepare_input_data(
762-
input_args: Any,
763761
input_kwargs: dict[str, Any],
764762
) -> dict[str, str]:
765763
"""
766764
Convert raw input to a structured dictionary {'key1': 'value1', 'key2': 'value2'}.
767765
"""
768-
769-
def prepare_str(str_in: str) -> dict[str, str]:
770-
str_in = str_in.replace(" ", "")
771-
key_val_list: list[str] = str_in.split("=")
772-
if len(key_val_list) != 2:
773-
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
774-
if len(key_val_list[0]) == 0:
775-
raise ModelicaSystemError(f"Empty key: {str_in}")
776-
777-
input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}
778-
779-
return input_data_from_str
780-
781766
input_data: dict[str, str] = {}
782767

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

887843
def setContinuous(
888844
self,
889-
*args: Any,
890845
**kwargs: dict[str, Any],
891846
) -> bool:
892847
"""
893-
This method is used to set continuous values. It can be called:
894-
with a sequence of continuous name and assigning corresponding values as arguments as show in the example below:
895-
usage
896-
>>> setContinuous("Name=value") # depreciated
897-
>>> setContinuous(["Name1=value1","Name2=value2"]) # depreciated
848+
This method is used to set continuous values.
898849
850+
usage:
899851
>>> setContinuous(Name1="value1", Name2="value2")
900852
>>> param = {"Name1": "value1", "Name2": "value2"}
901853
>>> setContinuous(**param)
902854
"""
903-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
855+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
904856

905857
return self._set_method_helper(
906858
inputdata=inputdata,
@@ -910,21 +862,17 @@ def setContinuous(
910862

911863
def setParameters(
912864
self,
913-
*args: Any,
914865
**kwargs: dict[str, Any],
915866
) -> bool:
916867
"""
917-
This method is used to set parameter values. It can be called:
918-
with a sequence of parameter name and assigning corresponding value as arguments as show in the example below:
919-
usage
920-
>>> setParameters("Name=value") # depreciated
921-
>>> setParameters(["Name1=value1","Name2=value2"]) # depreciated
868+
This method is used to set parameter values
922869
870+
usage:
923871
>>> setParameters(Name1="value1", Name2="value2")
924872
>>> param = {"Name1": "value1", "Name2": "value2"}
925873
>>> setParameters(**param)
926874
"""
927-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
875+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
928876

929877
return self._set_method_helper(
930878
inputdata=inputdata,
@@ -934,22 +882,17 @@ def setParameters(
934882

935883
def setSimulationOptions(
936884
self,
937-
*args: Any,
938885
**kwargs: dict[str, Any],
939886
) -> bool:
940887
"""
941-
This method is used to set simulation options. It can be called:
942-
with a sequence of simulation options name and assigning corresponding values as arguments as show in the
943-
example below:
944-
usage
945-
>>> setSimulationOptions("Name=value") # depreciated
946-
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
888+
This method is used to set simulation options.
947889
890+
usage:
948891
>>> setSimulationOptions(Name1="value1", Name2="value2")
949892
>>> param = {"Name1": "value1", "Name2": "value2"}
950893
>>> setSimulationOptions(**param)
951894
"""
952-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
895+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
953896

954897
return self._set_method_helper(
955898
inputdata=inputdata,
@@ -959,22 +902,17 @@ def setSimulationOptions(
959902

960903
def setLinearizationOptions(
961904
self,
962-
*args: Any,
963905
**kwargs: dict[str, Any],
964906
) -> bool:
965907
"""
966-
This method is used to set linearization options. It can be called:
967-
with a sequence of linearization options name and assigning corresponding value as arguments as show in the
968-
example below
969-
usage
970-
>>> setLinearizationOptions("Name=value") # depreciated
971-
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
908+
This method is used to set linearization options.
972909
910+
usage:
973911
>>> setLinearizationOptions(Name1="value1", Name2="value2")
974912
>>> param = {"Name1": "value1", "Name2": "value2"}
975913
>>> setLinearizationOptions(**param)
976914
"""
977-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
915+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
978916

979917
return self._set_method_helper(
980918
inputdata=inputdata,
@@ -984,22 +922,17 @@ def setLinearizationOptions(
984922

985923
def setOptimizationOptions(
986924
self,
987-
*args: Any,
988925
**kwargs: dict[str, Any],
989926
) -> bool:
990927
"""
991-
This method is used to set optimization options. It can be called:
992-
with a sequence of optimization options name and assigning corresponding values as arguments as show in the
993-
example below:
994-
usage
995-
>>> setOptimizationOptions("Name=value") # depreciated
996-
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
928+
This method is used to set optimization options.
997929
930+
usage:
998931
>>> setOptimizationOptions(Name1="value1", Name2="value2")
999932
>>> param = {"Name1": "value1", "Name2": "value2"}
1000933
>>> setOptimizationOptions(**param)
1001934
"""
1002-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
935+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
1003936

1004937
return self._set_method_helper(
1005938
inputdata=inputdata,
@@ -1013,19 +946,17 @@ def setInputs(
1013946
**kwargs: dict[str, Any],
1014947
) -> bool:
1015948
"""
1016-
This method is used to set input values. It can be called with a sequence of input name and assigning
1017-
corresponding values as arguments as show in the example below. Compared to other set*() methods this is a
1018-
special case as value could be a list of tuples - these are converted to a string in _prepare_input_data()
1019-
and restored here via ast.literal_eval().
949+
This method is used to set input values.
1020950
1021-
>>> setInputs("Name=value") # depreciated
1022-
>>> setInputs(["Name1=value1","Name2=value2"]) # depreciated
951+
Compared to other set*() methods this is a special case as value could be a list of tuples - these are
952+
converted to a string in _prepare_input_data() and restored here via ast.literal_eval().
1023953
954+
usage:
1024955
>>> setInputs(Name1="value1", Name2="value2")
1025956
>>> param = {"Name1": "value1", "Name2": "value2"}
1026957
>>> setInputs(**param)
1027958
"""
1028-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
959+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
1029960

1030961
for key, val in inputdata.items():
1031962
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)