Skip to content

Commit a07b78c

Browse files
committed
Merge branch 'remove_deprecated-ModelicaSystem_rewrite_set_functions2' into syntron_RFC-local-remove
2 parents 8ad0d08 + e02f804 commit a07b78c

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
@@ -150,14 +150,62 @@ def _set_compatibility_helper(
150150
pkey: str,
151151
args: Any,
152152
kwargs: dict[str, Any],
153-
) -> Any:
154-
param = None
153+
) -> dict[str, Any]:
154+
input_args = []
155155
if len(args) == 1:
156-
param = args[0]
157-
if param is None and pkey in kwargs:
158-
param = kwargs[pkey]
159-
160-
return param
156+
input_args.append(args[0])
157+
elif pkey in kwargs:
158+
input_args.append(kwargs[pkey])
159+
160+
# the code below is based on _prepare_input_data2()
161+
162+
def prepare_str(str_in: str) -> dict[str, str]:
163+
str_in = str_in.replace(" ", "")
164+
key_val_list: list[str] = str_in.split("=")
165+
if len(key_val_list) != 2:
166+
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
167+
if len(key_val_list[0]) == 0:
168+
raise ModelicaSystemError(f"Empty key: {str_in}")
169+
170+
input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}
171+
172+
return input_data_from_str
173+
174+
input_data: dict[str, str] = {}
175+
176+
if input_args is None:
177+
return input_data
178+
179+
for input_arg in input_args:
180+
if isinstance(input_arg, str):
181+
warnings.warn(message="The definition of values to set should use a dictionary, "
182+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
183+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
184+
category=DeprecationWarning,
185+
stacklevel=3)
186+
input_data = input_data | prepare_str(input_arg)
187+
elif isinstance(input_arg, list):
188+
warnings.warn(message="The definition of values to set should use a dictionary, "
189+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
190+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
191+
category=DeprecationWarning,
192+
stacklevel=3)
193+
194+
for item in input_arg:
195+
if not isinstance(item, str):
196+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
197+
input_data = input_data | prepare_str(item)
198+
elif isinstance(input_arg, dict):
199+
input_arg_str: dict[str, str] = {}
200+
for key, val in input_arg.items():
201+
if not isinstance(key, str) or len(key) == 0:
202+
raise ModelicaSystemError(f"Invalid key for set*() functions: {repr(key)}")
203+
input_arg_str[key] = str(val).replace(' ', '')
204+
input_data = input_data | input_arg_str
205+
else:
206+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")
207+
208+
return input_data
161209

162210
def setContinuous(
163211
self,
@@ -177,10 +225,7 @@ def setContinuous(
177225
```
178226
"""
179227
param = self._set_compatibility_helper(pkey='cvals', args=args, kwargs=kwargs)
180-
if param is None:
181-
raise ModelicaSystemError("Invalid input for setContinuous() (v4.0.0 compatibility mode).")
182-
183-
return super().setContinuous(param)
228+
return super().setContinuous(**param)
184229

185230
def setParameters(
186231
self,
@@ -200,10 +245,7 @@ def setParameters(
200245
```
201246
"""
202247
param = self._set_compatibility_helper(pkey='pvals', args=args, kwargs=kwargs)
203-
if param is None:
204-
raise ModelicaSystemError("Invalid input for setParameters() (v4.0.0 compatibility mode).")
205-
206-
return super().setParameters(param)
248+
return super().setParameters(**param)
207249

208250
def setOptimizationOptions(
209251
self,
@@ -223,10 +265,7 @@ def setOptimizationOptions(
223265
```
224266
"""
225267
param = self._set_compatibility_helper(pkey='optimizationOptions', args=args, kwargs=kwargs)
226-
if param is None:
227-
raise ModelicaSystemError("Invalid input for setOptimizationOptions() (v4.0.0 compatibility mode).")
228-
229-
return super().setOptimizationOptions(param)
268+
return super().setOptimizationOptions(**param)
230269

231270
def setInputs(
232271
self,
@@ -246,10 +285,7 @@ def setInputs(
246285
```
247286
"""
248287
param = self._set_compatibility_helper(pkey='name', args=args, kwargs=kwargs)
249-
if param is None:
250-
raise ModelicaSystemError("Invalid input for setInputs() (v4.0.0 compatibility mode).")
251-
252-
return super().setInputs(param)
288+
return super().setInputs(**param)
253289

254290
def setSimulationOptions(
255291
self,
@@ -269,10 +305,7 @@ def setSimulationOptions(
269305
```
270306
"""
271307
param = self._set_compatibility_helper(pkey='simOptions', args=args, kwargs=kwargs)
272-
if param is None:
273-
raise ModelicaSystemError("Invalid input for setSimulationOptions() (v4.0.0 compatibility mode).")
274-
275-
return super().setSimulationOptions(param)
308+
return super().setSimulationOptions(**param)
276309

277310
def setLinearizationOptions(
278311
self,
@@ -292,10 +325,7 @@ def setLinearizationOptions(
292325
```
293326
"""
294327
param = self._set_compatibility_helper(pkey='linearizationOptions', args=args, kwargs=kwargs)
295-
if param is None:
296-
raise ModelicaSystemError("Invalid input for setLinearizationOptions() (v4.0.0 compatibility mode).")
297-
298-
return super().setLinearizationOptions(param)
328+
return super().setLinearizationOptions(**param)
299329

300330
def getContinuous(
301331
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
@@ -740,56 +739,13 @@ def simulate(
740739

741740
@staticmethod
742741
def _prepare_input_data(
743-
input_args: Any,
744742
input_kwargs: dict[str, Any],
745743
) -> dict[str, str]:
746744
"""
747745
Convert raw input to a structured dictionary {'key1': 'value1', 'key2': 'value2'}.
748746
"""
749-
750-
def prepare_str(str_in: str) -> dict[str, str]:
751-
str_in = str_in.replace(" ", "")
752-
key_val_list: list[str] = str_in.split("=")
753-
if len(key_val_list) != 2:
754-
raise ModelicaSystemError(f"Invalid 'key=value' pair: {str_in}")
755-
if len(key_val_list[0]) == 0:
756-
raise ModelicaSystemError(f"Empty key: {str_in}")
757-
758-
input_data_from_str: dict[str, str] = {str(key_val_list[0]): str(key_val_list[1])}
759-
760-
return input_data_from_str
761-
762747
input_data: dict[str, str] = {}
763748

764-
for input_arg in input_args:
765-
if isinstance(input_arg, str):
766-
warnings.warn(message="The definition of values to set should use a dictionary, "
767-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
768-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
769-
category=DeprecationWarning,
770-
stacklevel=3)
771-
input_data = input_data | prepare_str(input_arg)
772-
elif isinstance(input_arg, list):
773-
warnings.warn(message="The definition of values to set should use a dictionary, "
774-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
775-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
776-
category=DeprecationWarning,
777-
stacklevel=3)
778-
779-
for item in input_arg:
780-
if not isinstance(item, str):
781-
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
782-
input_data = input_data | prepare_str(item)
783-
elif isinstance(input_arg, dict):
784-
input_arg_str: dict[str, str] = {}
785-
for key, val in input_arg.items():
786-
if not isinstance(key, str) or len(key) == 0:
787-
raise ModelicaSystemError(f"Invalid key for set*() functions: {repr(key)}")
788-
input_arg_str[key] = str(val)
789-
input_data = input_data | input_arg_str
790-
else:
791-
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")
792-
793749
if len(input_kwargs):
794750
for key, val in input_kwargs.items():
795751
# ensure all values are strings to align it on one type: dict[str, str]
@@ -867,21 +823,17 @@ def isParameterChangeable(
867823

868824
def setContinuous(
869825
self,
870-
*args: Any,
871826
**kwargs: dict[str, Any],
872827
) -> bool:
873828
"""
874-
This method is used to set continuous values. It can be called:
875-
with a sequence of continuous name and assigning corresponding values as arguments as show in the example below:
876-
usage
877-
>>> setContinuous("Name=value") # depreciated
878-
>>> setContinuous(["Name1=value1","Name2=value2"]) # depreciated
829+
This method is used to set continuous values.
879830
831+
usage:
880832
>>> setContinuous(Name1="value1", Name2="value2")
881833
>>> param = {"Name1": "value1", "Name2": "value2"}
882834
>>> setContinuous(**param)
883835
"""
884-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
836+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
885837

886838
return self._set_method_helper(
887839
inputdata=inputdata,
@@ -891,21 +843,17 @@ def setContinuous(
891843

892844
def setParameters(
893845
self,
894-
*args: Any,
895846
**kwargs: dict[str, Any],
896847
) -> bool:
897848
"""
898-
This method is used to set parameter values. It can be called:
899-
with a sequence of parameter name and assigning corresponding value as arguments as show in the example below:
900-
usage
901-
>>> setParameters("Name=value") # depreciated
902-
>>> setParameters(["Name1=value1","Name2=value2"]) # depreciated
849+
This method is used to set parameter values
903850
851+
usage:
904852
>>> setParameters(Name1="value1", Name2="value2")
905853
>>> param = {"Name1": "value1", "Name2": "value2"}
906854
>>> setParameters(**param)
907855
"""
908-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
856+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
909857

910858
return self._set_method_helper(
911859
inputdata=inputdata,
@@ -915,22 +863,17 @@ def setParameters(
915863

916864
def setSimulationOptions(
917865
self,
918-
*args: Any,
919866
**kwargs: dict[str, Any],
920867
) -> bool:
921868
"""
922-
This method is used to set simulation options. It can be called:
923-
with a sequence of simulation options name and assigning corresponding values as arguments as show in the
924-
example below:
925-
usage
926-
>>> setSimulationOptions("Name=value") # depreciated
927-
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
869+
This method is used to set simulation options.
928870
871+
usage:
929872
>>> setSimulationOptions(Name1="value1", Name2="value2")
930873
>>> param = {"Name1": "value1", "Name2": "value2"}
931874
>>> setSimulationOptions(**param)
932875
"""
933-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
876+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
934877

935878
return self._set_method_helper(
936879
inputdata=inputdata,
@@ -940,22 +883,17 @@ def setSimulationOptions(
940883

941884
def setLinearizationOptions(
942885
self,
943-
*args: Any,
944886
**kwargs: dict[str, Any],
945887
) -> bool:
946888
"""
947-
This method is used to set linearization options. It can be called:
948-
with a sequence of linearization options name and assigning corresponding value as arguments as show in the
949-
example below
950-
usage
951-
>>> setLinearizationOptions("Name=value") # depreciated
952-
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
889+
This method is used to set linearization options.
953890
891+
usage:
954892
>>> setLinearizationOptions(Name1="value1", Name2="value2")
955893
>>> param = {"Name1": "value1", "Name2": "value2"}
956894
>>> setLinearizationOptions(**param)
957895
"""
958-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
896+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
959897

960898
return self._set_method_helper(
961899
inputdata=inputdata,
@@ -965,22 +903,17 @@ def setLinearizationOptions(
965903

966904
def setOptimizationOptions(
967905
self,
968-
*args: Any,
969906
**kwargs: dict[str, Any],
970907
) -> bool:
971908
"""
972-
This method is used to set optimization options. It can be called:
973-
with a sequence of optimization options name and assigning corresponding values as arguments as show in the
974-
example below:
975-
usage
976-
>>> setOptimizationOptions("Name=value") # depreciated
977-
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
909+
This method is used to set optimization options.
978910
911+
usage:
979912
>>> setOptimizationOptions(Name1="value1", Name2="value2")
980913
>>> param = {"Name1": "value1", "Name2": "value2"}
981914
>>> setOptimizationOptions(**param)
982915
"""
983-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
916+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
984917

985918
return self._set_method_helper(
986919
inputdata=inputdata,
@@ -994,19 +927,17 @@ def setInputs(
994927
**kwargs: dict[str, Any],
995928
) -> bool:
996929
"""
997-
This method is used to set input values. It can be called with a sequence of input name and assigning
998-
corresponding values as arguments as show in the example below. Compared to other set*() methods this is a
999-
special case as value could be a list of tuples - these are converted to a string in _prepare_input_data()
1000-
and restored here via ast.literal_eval().
930+
This method is used to set input values.
1001931
1002-
>>> setInputs("Name=value") # depreciated
1003-
>>> setInputs(["Name1=value1","Name2=value2"]) # depreciated
932+
Compared to other set*() methods this is a special case as value could be a list of tuples - these are
933+
converted to a string in _prepare_input_data() and restored here via ast.literal_eval().
1004934
935+
usage:
1005936
>>> setInputs(Name1="value1", Name2="value2")
1006937
>>> param = {"Name1": "value1", "Name2": "value2"}
1007938
>>> setInputs(**param)
1008939
"""
1009-
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
940+
inputdata = self._prepare_input_data(input_kwargs=kwargs)
1010941

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