Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,6 @@ def __init__(
self._file_name = pathlib.Path(fileName).resolve() if fileName is not None else None # Model file/package name
self._has_inputs = False # for model with input quantity
self._simulated = False # True if the model has already been simulated
self._csvFile: Optional[pathlib.Path] = None # for storing inputs condition
self._result_file: Optional[pathlib.Path] = None # for storing result file
self._variable_filter = variableFilter

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

def simulate_cmd(
self,
resultfile: pathlib.Path,
result_file: pathlib.Path,
simflags: Optional[str] = None,
simargs: Optional[dict[str, Optional[str | dict[str, str]]]] = None,
timeout: Optional[float] = None,
Expand All @@ -934,7 +933,7 @@ def simulate_cmd(

Parameters
----------
resultfile
result_file
simflags
simargs
timeout
Expand All @@ -947,7 +946,7 @@ def simulate_cmd(
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)

# always define the result file to use
om_cmd.arg_set(key="r", val=resultfile.as_posix())
om_cmd.arg_set(key="r", val=result_file.as_posix())

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

if self._has_inputs: # if model has input quantities
# csvfile is based on name used for result file
csvfile = result_file.parent / f"{result_file.stem}.csv"

for i in self._inputs:
val = self._inputs[i]
if val is None:
Expand All @@ -979,9 +981,11 @@ def simulate_cmd(
raise ModelicaSystemError(f"startTime not matched for Input {i}!")
if float(self._simulate_options["stopTime"]) != val[-1][0]:
raise ModelicaSystemError(f"stopTime not matched for Input {i}!")
self._csvFile = self._createCSVData() # create csv file

om_cmd.arg_set(key="csvInput", val=self._csvFile.as_posix())
# write csv file and store the name
csvfile = self._createCSVData(csvfile=csvfile)

om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())

return om_cmd

Expand Down Expand Up @@ -1019,7 +1023,7 @@ def simulate(
self._result_file = self._tempdir / resultfile

om_cmd = self.simulate_cmd(
resultfile=self._result_file,
result_file=self._result_file,
simflags=simflags,
simargs=simargs,
timeout=timeout,
Expand Down Expand Up @@ -1272,7 +1276,11 @@ def _checkValidInputs(self, name):
else:
raise ModelicaSystemError('Error!!! Value must be in tuple format')

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

Expand Down Expand Up @@ -1313,13 +1321,14 @@ def _createCSVData(self) -> pathlib.Path:
]
csv_rows.append(row)

csvFile = self._tempdir / f'{self._model_name}.csv'
if csvfile is None:
csvfile = self._tempdir / f'{self._model_name}.csv'

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

return csvFile
return csvfile

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

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

Expand Down
6 changes: 4 additions & 2 deletions tests/test_ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,14 @@ def test_simulate_inputs(tmp_path):
"u1=[(0.0, 0), (1.0, 1)]",
"u2=[(0.0, 0), (0.25, 0.5), (0.5, 1.0), (1.0, 0)]",
])
mod.simulate()
assert pathlib.Path(mod._csvFile).read_text() == """time,u1,u2,end
csv_file = mod._createCSVData()
assert pathlib.Path(csv_file).read_text() == """time,u1,u2,end
0.0,0.0,0.0,0
0.25,0.25,0.5,0
0.5,0.5,1.0,0
1.0,1.0,0.0,0
"""

mod.simulate()
y = mod.getSolutions("y")[0]
assert np.isclose(y[-1], 1.0)
Loading