Skip to content

Commit 0b8fec5

Browse files
syntronadeas31
andauthored
[ModelicaSystem] improve set functions (#345)
* [ModelicaSystem] update input handling for set*() functions * use a Pythonic way for input: setParameters(a=123) param = {'a': 123} setParameters(**param) see input by SengerM in PR #326 * [test_optimization] update due to changes in set*() functions * [test_ModelicaSystem] update due to changes in set*() functions * [test_linearization] update due to changes in set*() functions * [ModelicaSystem] consider dict input for set*() functions --------- Co-authored-by: Adeel Asghar <[email protected]>
1 parent eec4e23 commit 0b8fec5

File tree

4 files changed

+114
-73
lines changed

4 files changed

+114
-73
lines changed

OMPython/ModelicaSystem.py

Lines changed: 79 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1220,7 +1220,8 @@ def getSolutions(
12201220

12211221
@staticmethod
12221222
def _prepare_input_data(
1223-
raw_input: str | list[str] | dict[str, Any],
1223+
input_args: Any,
1224+
input_kwargs: dict[str, Any],
12241225
) -> dict[str, str]:
12251226
"""
12261227
Convert raw input to a structured dictionary {'key1': 'value1', 'key2': 'value2'}.
@@ -1238,38 +1239,44 @@ def prepare_str(str_in: str) -> dict[str, str]:
12381239

12391240
input_data: dict[str, str] = {}
12401241

1241-
if isinstance(raw_input, str):
1242-
warnings.warn(message="The definition of values to set should use a dictionary, "
1243-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
1244-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
1245-
category=DeprecationWarning,
1246-
stacklevel=3)
1247-
return prepare_str(raw_input)
1248-
1249-
if isinstance(raw_input, list):
1250-
warnings.warn(message="The definition of values to set should use a dictionary, "
1251-
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
1252-
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
1253-
category=DeprecationWarning,
1254-
stacklevel=3)
1255-
1256-
for item in raw_input:
1257-
input_data |= prepare_str(item)
1258-
1259-
return input_data
1260-
1261-
if isinstance(raw_input, dict):
1262-
for key, val in raw_input.items():
1263-
# convert all values to strings to align it on one type: dict[str, str]
1264-
# spaces have to be removed as setInput() could take list of tuples as input and spaces would
1265-
str_val = str(val).replace(' ', '')
1242+
for input_arg in input_args:
1243+
if isinstance(input_arg, str):
1244+
warnings.warn(message="The definition of values to set should use a dictionary, "
1245+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
1246+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
1247+
category=DeprecationWarning,
1248+
stacklevel=3)
1249+
input_data = input_data | prepare_str(input_arg)
1250+
elif isinstance(input_arg, list):
1251+
warnings.warn(message="The definition of values to set should use a dictionary, "
1252+
"i.e. {'key1': 'val1', 'key2': 'val2', ...}. Please convert all cases which "
1253+
"use a string ('key=val') or list ['key1=val1', 'key2=val2', ...]",
1254+
category=DeprecationWarning,
1255+
stacklevel=3)
1256+
1257+
for item in input_arg:
1258+
if not isinstance(item, str):
1259+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(item)}!")
1260+
input_data = input_data | prepare_str(item)
1261+
elif isinstance(input_arg, dict):
1262+
input_data = input_data | input_arg
1263+
else:
1264+
raise ModelicaSystemError(f"Invalid input data type for set*() function: {type(input_arg)}!")
1265+
1266+
if len(input_kwargs):
1267+
for key, val in input_kwargs.items():
1268+
# ensure all values are strings to align it on one type: dict[str, str]
1269+
if not isinstance(val, str):
1270+
# spaces have to be removed as setInput() could take list of tuples as input and spaces would
1271+
# result in an error on recreating the input data
1272+
str_val = str(val).replace(' ', '')
1273+
else:
1274+
str_val = val
12661275
if ' ' in key or ' ' in str_val:
12671276
raise ModelicaSystemError(f"Spaces not allowed in key/value pairs: {repr(key)} = {repr(val)}!")
12681277
input_data[key] = str_val
12691278

1270-
return input_data
1271-
1272-
raise ModelicaSystemError(f"Invalid type of input: {type(raw_input)}")
1279+
return input_data
12731280

12741281
def _set_method_helper(
12751282
self,
@@ -1301,8 +1308,7 @@ def _set_method_helper(
13011308

13021309
for key, val in inputdata.items():
13031310
if key not in classdata:
1304-
raise ModelicaSystemError("Unhandled case in setMethodHelper.apply_single() - "
1305-
f"{repr(key)} is not a {repr(datatype)} variable")
1311+
raise ModelicaSystemError(f"Invalid variable for type {repr(datatype)}: {repr(key)}")
13061312

13071313
if datatype == "parameter" and not self.isParameterChangeable(key):
13081314
raise ModelicaSystemError(f"It is not possible to set the parameter {repr(key)}. It seems to be "
@@ -1330,17 +1336,21 @@ def isParameterChangeable(
13301336

13311337
def setContinuous(
13321338
self,
1333-
cvals: str | list[str] | dict[str, Any],
1339+
*args: Any,
1340+
**kwargs: dict[str, Any],
13341341
) -> bool:
13351342
"""
13361343
This method is used to set continuous values. It can be called:
13371344
with a sequence of continuous name and assigning corresponding values as arguments as show in the example below:
13381345
usage
13391346
>>> setContinuous("Name=value") # depreciated
13401347
>>> setContinuous(["Name1=value1","Name2=value2"]) # depreciated
1341-
>>> setContinuous(cvals={"Name1": "value1", "Name2": "value2"})
1348+
1349+
>>> setContinuous(Name1="value1", Name2="value2")
1350+
>>> param = {"Name1": "value1", "Name2": "value2"}
1351+
>>> setContinuous(**param)
13421352
"""
1343-
inputdata = self._prepare_input_data(raw_input=cvals)
1353+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
13441354

13451355
return self._set_method_helper(
13461356
inputdata=inputdata,
@@ -1350,17 +1360,21 @@ def setContinuous(
13501360

13511361
def setParameters(
13521362
self,
1353-
pvals: str | list[str] | dict[str, Any],
1363+
*args: Any,
1364+
**kwargs: dict[str, Any],
13541365
) -> bool:
13551366
"""
13561367
This method is used to set parameter values. It can be called:
13571368
with a sequence of parameter name and assigning corresponding value as arguments as show in the example below:
13581369
usage
13591370
>>> setParameters("Name=value") # depreciated
13601371
>>> setParameters(["Name1=value1","Name2=value2"]) # depreciated
1361-
>>> setParameters(pvals={"Name1": "value1", "Name2": "value2"})
1372+
1373+
>>> setParameters(Name1="value1", Name2="value2")
1374+
>>> param = {"Name1": "value1", "Name2": "value2"}
1375+
>>> setParameters(**param)
13621376
"""
1363-
inputdata = self._prepare_input_data(raw_input=pvals)
1377+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
13641378

13651379
return self._set_method_helper(
13661380
inputdata=inputdata,
@@ -1370,17 +1384,21 @@ def setParameters(
13701384

13711385
def setSimulationOptions(
13721386
self,
1373-
simOptions: str | list[str] | dict[str, Any],
1387+
*args: Any,
1388+
**kwargs: dict[str, Any],
13741389
) -> bool:
13751390
"""
13761391
This method is used to set simulation options. It can be called:
13771392
with a sequence of simulation options name and assigning corresponding values as arguments as show in the example below:
13781393
usage
13791394
>>> setSimulationOptions("Name=value") # depreciated
13801395
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
1381-
>>> setSimulationOptions(simOptions={"Name1": "value1", "Name2": "value2"})
1396+
1397+
>>> setSimulationOptions(Name1="value1", Name2="value2")
1398+
>>> param = {"Name1": "value1", "Name2": "value2"}
1399+
>>> setSimulationOptions(**param)
13821400
"""
1383-
inputdata = self._prepare_input_data(raw_input=simOptions)
1401+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
13841402

13851403
return self._set_method_helper(
13861404
inputdata=inputdata,
@@ -1390,17 +1408,21 @@ def setSimulationOptions(
13901408

13911409
def setLinearizationOptions(
13921410
self,
1393-
linearizationOptions: str | list[str] | dict[str, Any],
1411+
*args: Any,
1412+
**kwargs: dict[str, Any],
13941413
) -> bool:
13951414
"""
13961415
This method is used to set linearization options. It can be called:
13971416
with a sequence of linearization options name and assigning corresponding value as arguments as show in the example below
13981417
usage
13991418
>>> setLinearizationOptions("Name=value") # depreciated
14001419
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
1401-
>>> setLinearizationOptions(linearizationOtions={"Name1": "value1", "Name2": "value2"})
1420+
1421+
>>> setLinearizationOptions(Name1="value1", Name2="value2")
1422+
>>> param = {"Name1": "value1", "Name2": "value2"}
1423+
>>> setLinearizationOptions(**param)
14021424
"""
1403-
inputdata = self._prepare_input_data(raw_input=linearizationOptions)
1425+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
14041426

14051427
return self._set_method_helper(
14061428
inputdata=inputdata,
@@ -1410,17 +1432,21 @@ def setLinearizationOptions(
14101432

14111433
def setOptimizationOptions(
14121434
self,
1413-
optimizationOptions: str | list[str] | dict[str, Any],
1435+
*args: Any,
1436+
**kwargs: dict[str, Any],
14141437
) -> bool:
14151438
"""
14161439
This method is used to set optimization options. It can be called:
14171440
with a sequence of optimization options name and assigning corresponding values as arguments as show in the example below:
14181441
usage
14191442
>>> setOptimizationOptions("Name=value") # depreciated
14201443
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
1421-
>>> setOptimizationOptions(optimizationOptions={"Name1": "value1", "Name2": "value2"})
1444+
1445+
>>> setOptimizationOptions(Name1="value1", Name2="value2")
1446+
>>> param = {"Name1": "value1", "Name2": "value2"}
1447+
>>> setOptimizationOptions(**param)
14221448
"""
1423-
inputdata = self._prepare_input_data(raw_input=optimizationOptions)
1449+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
14241450

14251451
return self._set_method_helper(
14261452
inputdata=inputdata,
@@ -1430,7 +1456,8 @@ def setOptimizationOptions(
14301456

14311457
def setInputs(
14321458
self,
1433-
name: str | list[str] | dict[str, Any],
1459+
*args: Any,
1460+
**kwargs: dict[str, Any],
14341461
) -> bool:
14351462
"""
14361463
This method is used to set input values. It can be called with a sequence of input name and assigning
@@ -1440,9 +1467,12 @@ def setInputs(
14401467
14411468
>>> setInputs("Name=value") # depreciated
14421469
>>> setInputs(["Name1=value1","Name2=value2"]) # depreciated
1443-
>>> setInputs(name={"Name1": "value1", "Name2": "value2"})
1470+
1471+
>>> setInputs(Name1="value1", Name2="value2")
1472+
>>> param = {"Name1": "value1", "Name2": "value2"}
1473+
>>> setInputs(**param)
14441474
"""
1445-
inputdata = self._prepare_input_data(raw_input=name)
1475+
inputdata = self._prepare_input_data(input_args=args, input_kwargs=kwargs)
14461476

14471477
for key, val in inputdata.items():
14481478
if key not in self._inputs:

tests/test_ModelicaSystem.py

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ def test_setParameters():
3434
model_path = omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/"
3535
mod = OMPython.ModelicaSystem(model_path + "BouncingBall.mo", "BouncingBall")
3636

37-
# method 1
38-
mod.setParameters(pvals={"e": 1.234})
39-
mod.setParameters(pvals={"g": 321.0})
37+
# method 1 (test depreciated variants)
38+
mod.setParameters("e=1.234")
39+
mod.setParameters(["g=321.0"])
4040
assert mod.getParameters("e") == ["1.234"]
4141
assert mod.getParameters("g") == ["321.0"]
4242
assert mod.getParameters() == {
@@ -46,8 +46,9 @@ def test_setParameters():
4646
with pytest.raises(KeyError):
4747
mod.getParameters("thisParameterDoesNotExist")
4848

49-
# method 2
50-
mod.setParameters(pvals={"e": 21.3, "g": 0.12})
49+
# method 2 (new style)
50+
pvals = {"e": 21.3, "g": 0.12}
51+
mod.setParameters(**pvals)
5152
assert mod.getParameters() == {
5253
"e": "21.3",
5354
"g": "0.12",
@@ -64,8 +65,8 @@ def test_setSimulationOptions():
6465
mod = OMPython.ModelicaSystem(fileName=model_path + "BouncingBall.mo", modelName="BouncingBall")
6566

6667
# method 1
67-
mod.setSimulationOptions(simOptions={"stopTime": 1.234})
68-
mod.setSimulationOptions(simOptions={"tolerance": 1.1e-08})
68+
mod.setSimulationOptions(stopTime=1.234)
69+
mod.setSimulationOptions(tolerance=1.1e-08)
6970
assert mod.getSimulationOptions("stopTime") == ["1.234"]
7071
assert mod.getSimulationOptions("tolerance") == ["1.1e-08"]
7172
assert mod.getSimulationOptions(["tolerance", "stopTime"]) == ["1.1e-08", "1.234"]
@@ -77,7 +78,7 @@ def test_setSimulationOptions():
7778
mod.getSimulationOptions("thisOptionDoesNotExist")
7879

7980
# method 2
80-
mod.setSimulationOptions(simOptions={"stopTime": 2.1, "tolerance": "1.2e-08"})
81+
mod.setSimulationOptions(stopTime=2.1, tolerance=1.2e-08)
8182
d = mod.getSimulationOptions()
8283
assert d["stopTime"] == "2.1"
8384
assert d["tolerance"] == "1.2e-08"
@@ -119,7 +120,9 @@ def test_getSolutions(model_firstorder):
119120
a = -1
120121
tau = -1 / a
121122
stopTime = 5*tau
122-
mod.setSimulationOptions(simOptions={"stopTime": stopTime, "stepSize": 0.1, "tolerance": 1e-8})
123+
124+
simOptions = {"stopTime": stopTime, "stepSize": 0.1, "tolerance": 1e-8}
125+
mod.setSimulationOptions(**simOptions)
123126
mod.simulate()
124127

125128
x = mod.getSolutions("x")
@@ -298,7 +301,7 @@ def test_getters(tmp_path):
298301
x0 = 1.0
299302
x_analytical = -b/a + (x0 + b/a) * np.exp(a * stopTime)
300303
dx_analytical = (x0 + b/a) * a * np.exp(a * stopTime)
301-
mod.setSimulationOptions(simOptions={"stopTime": stopTime})
304+
mod.setSimulationOptions(stopTime=stopTime)
302305
mod.simulate()
303306

304307
# getOutputs after simulate()
@@ -327,7 +330,7 @@ def test_getters(tmp_path):
327330
mod.getContinuous("a") # a is a parameter
328331

329332
with pytest.raises(OMPython.ModelicaSystemError):
330-
mod.setSimulationOptions(simOptions={"thisOptionDoesNotExist": 3})
333+
mod.setSimulationOptions(thisOptionDoesNotExist=3)
331334

332335

333336
def test_simulate_inputs(tmp_path):
@@ -345,7 +348,8 @@ def test_simulate_inputs(tmp_path):
345348
""")
346349
mod = OMPython.ModelicaSystem(fileName=model_file.as_posix(), modelName="M_input")
347350

348-
mod.setSimulationOptions(simOptions={"stopTime": 1.0})
351+
simOptions = {"stopTime": 1.0}
352+
mod.setSimulationOptions(**simOptions)
349353

350354
# integrate zero (no setInputs call) - it should default to None -> 0
351355
assert mod.getInputs() == {
@@ -357,7 +361,7 @@ def test_simulate_inputs(tmp_path):
357361
assert np.isclose(y[-1], 0.0)
358362

359363
# integrate a constant
360-
mod.setInputs(name={"u1": 2.5})
364+
mod.setInputs(u1=2.5)
361365
assert mod.getInputs() == {
362366
"u1": [
363367
(0.0, 2.5),
@@ -374,7 +378,8 @@ def test_simulate_inputs(tmp_path):
374378
assert np.isclose(y[-1], 2.5)
375379

376380
# now let's integrate the sum of two ramps
377-
mod.setInputs(name={"u1": [(0.0, 0.0), (0.5, 2), (1.0, 0)]})
381+
inputs = {"u1": [(0.0, 0.0), (0.5, 2), (1.0, 0)]}
382+
mod.setInputs(**inputs)
378383
assert mod.getInputs("u1") == [[
379384
(0.0, 0.0),
380385
(0.5, 2.0),
@@ -387,17 +392,20 @@ def test_simulate_inputs(tmp_path):
387392
# let's try some edge cases
388393
# unmatched startTime
389394
with pytest.raises(OMPython.ModelicaSystemError):
390-
mod.setInputs(name={"u1": [(-0.5, 0.0), (1.0, 1)]})
395+
mod.setInputs(u1=[(-0.5, 0.0), (1.0, 1)])
391396
mod.simulate()
392397
# unmatched stopTime
393398
with pytest.raises(OMPython.ModelicaSystemError):
394-
mod.setInputs(name={"u1": [(0.0, 0.0), (0.5, 1)]})
399+
mod.setInputs(u1=[(0.0, 0.0), (0.5, 1)])
395400
mod.simulate()
396401

397402
# Let's use both inputs, but each one with different number of
398403
# samples. This has an effect when generating the csv file.
399-
mod.setInputs(name={"u1": [(0.0, 0), (1.0, 1)],
400-
"u2": [(0.0, 0), (0.25, 0.5), (0.5, 1.0), (1.0, 0)]})
404+
inputs = {
405+
"u1": [(0.0, 0), (1.0, 1)],
406+
"u2": [(0.0, 0), (0.25, 0.5), (0.5, 1.0), (1.0, 0)],
407+
}
408+
mod.setInputs(**inputs)
401409
csv_file = mod._createCSVData()
402410
assert pathlib.Path(csv_file).read_text() == """time,u1,u2,end
403411
0.0,0.0,0.0,0

tests/test_linearization.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ def test_getters(tmp_path):
6262
assert "startTime" in d
6363
assert "stopTime" in d
6464
assert mod.getLinearizationOptions(["stopTime", "startTime"]) == [d["stopTime"], d["startTime"]]
65-
mod.setLinearizationOptions(linearizationOptions={"stopTime": 0.02})
65+
mod.setLinearizationOptions(stopTime=0.02)
6666
assert mod.getLinearizationOptions("stopTime") == ["0.02"]
6767

68-
mod.setInputs(name={"u1": 10, "u2": 0})
68+
mod.setInputs(u1=10, u2=0)
6969
[A, B, C, D] = mod.linearize()
7070
g = float(mod.getParameters("g")[0])
7171
l = float(mod.getParameters("l")[0])

0 commit comments

Comments
 (0)