Skip to content

Commit 3e9c55b

Browse files
authored
ModelicaSystem - remove csvfile as class variable (#313)
* [ModelicaSystem] remove class variable csvFile; define name based on resultfile in simulate() reason: * variable not needed / used as class variable * using name based on resultfile allows to run the same model executable several times * [ModelicaSystem/test_ModelicaSystem] fix test (csvFile no longer a class variable) * [ModelicaSystem] fix rebase - use csvfile instead of csvFile * [test_ModelicaSystem] fix rebase fallout * [ModelicaSystem.simulate_cmd] fix result_file handling * rename resultfile => result_file * use local variable result_file and not self._result_file
1 parent 797eb84 commit 3e9c55b

File tree

2 files changed

+26
-15
lines changed

2 files changed

+26
-15
lines changed

OMPython/ModelicaSystem.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,6 @@ def __init__(
389389
self._file_name = pathlib.Path(fileName).resolve() if fileName is not None else None # Model file/package name
390390
self._has_inputs = False # for model with input quantity
391391
self._simulated = False # True if the model has already been simulated
392-
self._csvFile: Optional[pathlib.Path] = None # for storing inputs condition
393392
self._result_file: Optional[pathlib.Path] = None # for storing result file
394393
self._variable_filter = variableFilter
395394

@@ -917,7 +916,7 @@ def getOptimizationOptions(self, names: Optional[str | list[str]] = None) -> dic
917916

918917
def simulate_cmd(
919918
self,
920-
resultfile: pathlib.Path,
919+
result_file: pathlib.Path,
921920
simflags: Optional[str] = None,
922921
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
923922
timeout: Optional[float] = None,
@@ -934,7 +933,7 @@ def simulate_cmd(
934933
935934
Parameters
936935
----------
937-
resultfile
936+
result_file
938937
simflags
939938
simargs
940939
timeout
@@ -947,7 +946,7 @@ def simulate_cmd(
947946
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
948947

949948
# always define the result file to use
950-
om_cmd.arg_set(key="r", val=resultfile.as_posix())
949+
om_cmd.arg_set(key="r", val=result_file.as_posix())
951950

952951
# allow runtime simulation flags from user input
953952
if simflags is not None:
@@ -968,6 +967,9 @@ def simulate_cmd(
968967
om_cmd.arg_set(key="overrideFile", val=overrideFile.as_posix())
969968

970969
if self._has_inputs: # if model has input quantities
970+
# csvfile is based on name used for result file
971+
csvfile = result_file.parent / f"{result_file.stem}.csv"
972+
971973
for i in self._inputs:
972974
val = self._inputs[i]
973975
if val is None:
@@ -979,9 +981,11 @@ def simulate_cmd(
979981
raise ModelicaSystemError(f"startTime not matched for Input {i}!")
980982
if float(self._simulate_options["stopTime"]) != val[-1][0]:
981983
raise ModelicaSystemError(f"stopTime not matched for Input {i}!")
982-
self._csvFile = self._createCSVData() # create csv file
983984

984-
om_cmd.arg_set(key="csvInput", val=self._csvFile.as_posix())
985+
# write csv file and store the name
986+
csvfile = self._createCSVData(csvfile=csvfile)
987+
988+
om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())
985989

986990
return om_cmd
987991

@@ -1019,7 +1023,7 @@ def simulate(
10191023
self._result_file = self._tempdir / resultfile
10201024

10211025
om_cmd = self.simulate_cmd(
1022-
resultfile=self._result_file,
1026+
result_file=self._result_file,
10231027
simflags=simflags,
10241028
simargs=simargs,
10251029
timeout=timeout,
@@ -1272,7 +1276,11 @@ def _checkValidInputs(self, name):
12721276
else:
12731277
raise ModelicaSystemError('Error!!! Value must be in tuple format')
12741278

1275-
def _createCSVData(self) -> pathlib.Path:
1279+
def _createCSVData(self, csvfile: Optional[pathlib.Path] = None) -> pathlib.Path:
1280+
"""
1281+
Create a csv file with inputs for the simulation/optimization of the model. If csvfile is provided as argument,
1282+
this file is used; else a generic file name is created.
1283+
"""
12761284
start_time: float = float(self._simulate_options["startTime"])
12771285
stop_time: float = float(self._simulate_options["stopTime"])
12781286

@@ -1313,13 +1321,14 @@ def _createCSVData(self) -> pathlib.Path:
13131321
]
13141322
csv_rows.append(row)
13151323

1316-
csvFile = self._tempdir / f'{self._model_name}.csv'
1324+
if csvfile is None:
1325+
csvfile = self._tempdir / f'{self._model_name}.csv'
13171326

1318-
with open(file=csvFile, mode="w", encoding="utf-8", newline="") as fh:
1327+
with open(file=csvfile, mode="w", encoding="utf-8", newline="") as fh:
13191328
writer = csv.writer(fh)
13201329
writer.writerows(csv_rows)
13211330

1322-
return csvFile
1331+
return csvfile
13231332

13241333
def convertMo2Fmu(self, version: str = "2.0", fmuType: str = "me_cs",
13251334
fileNamePrefix: str = "<default>",
@@ -1463,8 +1472,8 @@ def load_module_from_path(module_name, file_path):
14631472
for l in tupleList:
14641473
if l[0] < float(self._simulate_options["startTime"]):
14651474
raise ModelicaSystemError('Input time value is less than simulation startTime')
1466-
self._csvFile = self._createCSVData()
1467-
om_cmd.arg_set(key="csvInput", val=self._csvFile.as_posix())
1475+
csvfile = self._createCSVData()
1476+
om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())
14681477

14691478
om_cmd.arg_set(key="l", val=str(lintime or self._linearization_options["stopTime"]))
14701479

tests/test_ModelicaSystem.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,12 +396,14 @@ def test_simulate_inputs(tmp_path):
396396
"u1=[(0.0, 0), (1.0, 1)]",
397397
"u2=[(0.0, 0), (0.25, 0.5), (0.5, 1.0), (1.0, 0)]",
398398
])
399-
mod.simulate()
400-
assert pathlib.Path(mod._csvFile).read_text() == """time,u1,u2,end
399+
csv_file = mod._createCSVData()
400+
assert pathlib.Path(csv_file).read_text() == """time,u1,u2,end
401401
0.0,0.0,0.0,0
402402
0.25,0.25,0.5,0
403403
0.5,0.5,1.0,0
404404
1.0,1.0,0.0,0
405405
"""
406+
407+
mod.simulate()
406408
y = mod.getSolutions("y")[0]
407409
assert np.isclose(y[-1], 1.0)

0 commit comments

Comments
 (0)